// ============================================================
// FitMinds — Shell: Sidebar + Header + small shared components
// ============================================================

const NAV_GROUPS = [
  { label: "Work", items: [
    { key: "dashboard", label: "Dashboard",   icon: "layout-dashboard" },
    { key: "bookings",  label: "Bookings",    icon: "calendar-check-2" },
    { key: "calendar",  label: "Calendar",    icon: "calendar-days" },
    { key: "schools",   label: "Schools",     icon: "school-2" },
    { key: "invoices",  label: "Invoices",    icon: "receipt" , badge: "3" },
    { key: "enquiries", label: "Enquiries",   icon: "inbox" ,   badge: "2" },
  ]},
  { label: "Coaching", items: [
    { key: "content",   label: "Content Portal", icon: "play-circle" },
    { key: "users",     label: "Users",          icon: "users" },
  ]},
  { label: "System", items: [
    { key: "reports",   label: "Reports",     icon: "bar-chart-3" },
    { key: "settings",  label: "Settings",    icon: "settings" },
  ]},
];

function BrandMark({ size = 38 }) {
  return (
    <div className="brand-mark" style={{ width: size, height: size }}>
      <svg width={size*0.56} height={size*0.56} viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
        {/* Running figure-ish abstract */}
        <circle cx="14" cy="6" r="2.2" fill="white" stroke="none"/>
        <path d="M5 20l3.5-5 3-1.5 2.5 2 2 4"/>
        <path d="M8.5 15L6 11l4-2 3.5 3"/>
        <path d="M3 12c1 1.5 3 2 5 2"/>
      </svg>
    </div>
  );
}

function Sidebar({ current, onNavigate, brand, onSwitchView, onLogout, auth }) {
  const displayName = (auth && auth.name) || "Guest";
  const displayRole = auth ? (AUTH_ROLE_LABELS[auth.role] || auth.role) : "";
  const displayAvatar = (auth && auth.avatar) || "??";
  return (
    <aside className="app-sidebar">
      <div className="brand-row">
        <BrandMark />
        <div style={{ flex: 1, minWidth: 0 }}>
          <div className="brand-name">{brand.name}</div>
          <div className="brand-sub">{brand.tagline}</div>
        </div>
      </div>

      {NAV_GROUPS.map((g, gi) => (
        <div key={gi}>
          <div className="sidebar-section-label">{g.label}</div>
          {g.items.map(item => {
            const active = current === item.key;
            return (
              <button key={item.key} className={`sidebar-row ${active ? "is-active" : ""}`} onClick={() => onNavigate(item.key)}>
                <Icon name={item.icon} size={17} />
                <span className="truncate" style={{ flex: 1 }}>{item.label}</span>
                {item.badge && <span className="sidebar-badge">{item.badge}</span>}
              </button>
            );
          })}
        </div>
      ))}

      <div className="sidebar-footer">
        <div className="user-chip" onClick={() => onSwitchView && onSwitchView()} title="Switch to parent/teacher view" style={{ cursor: onSwitchView ? "pointer" : "default" }}>
          <div className="avatar-sm">{displayAvatar}</div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div className="name truncate">{displayName}</div>
            <div className="role truncate">{displayRole}</div>
          </div>
          <button onClick={(e) => { e.stopPropagation(); onLogout && onLogout(); }}
            title="Log out"
            style={{
              background: "transparent", border: "none", cursor: "pointer",
              color: "oklch(1 0 0 / 70%)", padding: 6, borderRadius: 8,
              display: "inline-flex", alignItems: "center", justifyContent: "center",
            }}>
            <Icon name="log-out" size={15} />
          </button>
        </div>
      </div>
    </aside>
  );
}

function Header({ title, subtitle, action, onSearch }) {
  return (
    <header className="app-header">
      <div style={{ display: "flex", flexDirection: "column", justifyContent: "center" }}>
        <h1 className="page-title">{title}</h1>
        {subtitle && <p className="page-subtitle">{subtitle}</p>}
      </div>
      <div className="header-search">
        <Icon name="search" size={16} />
        <input placeholder="Search schools, bookings, invoices…" />
        <span className="kbd">⌘K</span>
      </div>
      <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
        <button className="icon-btn" title="Notifications"><Icon name="bell" /></button>
        <button className="icon-btn" title="Help"><Icon name="life-buoy" /></button>
        {action}
        <div className="avatar">RG</div>
      </div>
    </header>
  );
}

// ============================================================
// Shared components
// ============================================================

function Button({ children, variant = "primary", size = "md", icon, onClick, type, style, disabled }) {
  return (
    <button type={type || "button"} disabled={disabled}
      className={`btn btn-${variant} btn-${size}`} onClick={onClick} style={style}>
      {icon && <Icon name={icon} size={size === "sm" ? 13 : 15} />}
      {children}
    </button>
  );
}

function Chip({ children, tone = "neutral" }) {
  return <span className={`chip ${tone}`}>{children}</span>;
}

function StatCard({ label, value, icon, delta, tint }) {
  return (
    <div className="card stat-card card-lift">
      <p className="label">{label}</p>
      <p className="value tabnum">{value}</p>
      {delta && (
        <div className={`delta ${delta.dir}`}>
          <Icon name={delta.dir === "up" ? "trending-up" : "trending-down"} size={13} />
          {delta.text}
        </div>
      )}
      <div className={`stat-icon ${tint ? "tint-" + tint : ""}`}>
        <Icon name={icon} size={17} style={{ color: "#fff" }} />
      </div>
    </div>
  );
}

function Field({ label, hint, children }) {
  return (
    <label className="field">
      {label && <span className="field-label">{label}</span>}
      {children}
      {hint && <span className="field-hint">{hint}</span>}
    </label>
  );
}

function Switch({ on, onChange }) {
  return <div className={`switch ${on ? "is-on" : ""}`} onClick={() => onChange(!on)} role="switch" />;
}

function SchoolTile({ schoolId, size = 40 }) {
  const s = SCHOOL_BY_ID[schoolId];
  return <span className="school-tile" style={{ background: s.color, width: size, height: size, fontSize: size * 0.34 }}>{s.short}</span>;
}

function StatusChip({ status }) {
  const map = {
    active:    { tone: "green",   label: "Active" },
    upcoming:  { tone: "blue",    label: "Upcoming" },
    completed: { tone: "neutral", label: "Completed" },
    paid:      { tone: "green",   label: "Paid" },
    sent:      { tone: "blue",    label: "Sent" },
    draft:     { tone: "amber",   label: "Draft" },
    not_sent:  { tone: "neutral", label: "Not sent" },
    overdue:   { tone: "red",     label: "Overdue" },
    new:       { tone: "blue",    label: "New lead" },
    contacted: { tone: "amber",   label: "Contacted" },
    qualified: { tone: "violet",  label: "Qualified" },
    booked:    { tone: "green",   label: "Booked" },
    lost:      { tone: "neutral", label: "Lost" },
    invited:   { tone: "amber",   label: "Invited" },
  };
  const m = map[status] || map.neutral;
  return <Chip tone={m.tone}>{m.label}</Chip>;
}

function EmptyState({ icon, title, body, action }) {
  return (
    <div className="empty">
      <Icon name={icon} size={34} />
      <div style={{ fontSize: 15, fontWeight: 600, color: "var(--foreground)" }}>{title}</div>
      <div style={{ marginTop: 4 }}>{body}</div>
      {action && <div style={{ marginTop: 16 }}>{action}</div>}
    </div>
  );
}

function Tabs({ tabs, value, onChange }) {
  return (
    <div className="tabs-row">
      {tabs.map(t => (
        <button key={t.value} className={`tab ${value === t.value ? "is-active" : ""}`} onClick={() => onChange(t.value)}>{t.label}</button>
      ))}
    </div>
  );
}

function PageHead({ title, subtitle, action }) {
  return (
    <div className="flex items-start justify-between" style={{ marginBottom: 20 }}>
      <div>
        <h1 className="page-title">{title}</h1>
        {subtitle && <p className="page-subtitle">{subtitle}</p>}
      </div>
      {action}
    </div>
  );
}

Object.assign(window, {
  Sidebar, Header, Button, Chip, StatCard, Field, Switch,
  SchoolTile, StatusChip, EmptyState, Tabs, PageHead, BrandMark,
});
