// Main app shell — sidebar nav, topbar, page routing, tweaks panel

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accent": "lime",
  "dark": false,
  "layout": "timeline",
  "progress": "day1",
  "persona": "eng",
  "density": "regular"
}/*EDITMODE-END*/;

const NAV_GROUPS = [
  {
    label: "Onboarding",
    items: [
      { id: "dashboard", label: "Home", icon: "home" },
      { id: "meetings",  label: "Meetings",  icon: "calendar", badge: "11" },
      { id: "documents", label: "Documents", icon: "doc",      badge: "9"  },
      { id: "training",  label: "Training",  icon: "book",     dot: true   },
    ],
  },
  {
    label: "Setup",
    items: [
      { id: "insurance", label: "Healthcare & insurance", icon: "shield" },
      { id: "payroll",   label: "Pay & taxes",            icon: "dollar" },
      { id: "equipment", label: "IT & equipment",         icon: "laptop" },
      { id: "profile",   label: "Profile",                icon: "user"   },
    ],
  },
];

// Demo mode — no backend on shared hosting, state is in-memory only
window.onboardingAPI = null;

// ── Resolve persona from role string ────────────────────────────────────────
function roleToPersona(role) {
  if (!role) return "eng";
  const r = role.toLowerCase();
  if (r === "design" || r.includes("design")) return "design";
  if (r === "sales"  || r.includes("sales") || r.includes("account")) return "sales";
  return "eng";
}

// ── LoadingScreen ────────────────────────────────────────────────────────────
function LoadingScreen() {
  return (
    <div style={{
      position: "fixed", inset: 0, background: "var(--bg)",
      display: "flex", alignItems: "center", justifyContent: "center",
      flexDirection: "column", gap: 16,
    }}>
      <div className="brand" style={{ border: "none", padding: 0, gap: 10 }}>
        <div className="brand-mark">C</div>
        <div className="brand-name" style={{ fontSize: 18 }}>convoso</div>
      </div>
      <div className="muted" style={{ fontSize: 14 }}>Loading your onboarding…</div>
    </div>
  );
}

// ── App ───────────────────────────────────────────────────────────────────────
function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [page, setPage]         = React.useState("dashboard");
  const [employee, setEmployee] = React.useState(null);
  const [progress, setProgress] = React.useState(null);
  const [loading, setLoading]   = React.useState(true);

  // Read ?id= from URL
  const employeeId = React.useMemo(() => {
    const params = new URLSearchParams(window.location.search);
    return params.get("id");
  }, []);

  // Static demo mode — no backend calls
  React.useEffect(() => { setLoading(false); }, []);

  // Derive progress level from completed tasks
  const progressLevel = React.useMemo(() => {
    if (!progress) return t.progress;
    const done = new Set(progress.completed_tasks || []);
    // If all 19 tasks done → "done", if any week1/month1 done → "week1", else "day1"
    if (done.size >= 19) return "done";
    const week1Tasks = ["t8","t9","t10","t11","t12","t13","t14"];
    if (week1Tasks.some(id => done.has(id))) return "week1";
    return "day1";
  }, [progress, t.progress]);

  // Active hire name — real employee or demo
  const hire = React.useMemo(() => {
    if (employee) {
      return { name: employee.name, first: employee.first_name };
    }
    return NEW_HIRE;
  }, [employee]);

  // Apply theme attrs
  React.useEffect(() => {
    document.documentElement.dataset.theme   = t.dark    ? "dark" : "light";
    document.documentElement.dataset.accent  = t.accent;
    document.documentElement.dataset.density = t.density;
  }, [t.dark, t.accent, t.density]);

  const goto = (p) => {
    const map = { meetings: "meetings", documents: "documents", training: "training", insurance: "insurance" };
    setPage(map[p] || p);
    window.scrollTo({ top: 0, behavior: "instant" });
  };

  if (loading) return <LoadingScreen/>;

  // Signed-docs set from API (used by DocumentsPage)
  const savedSignedIds = new Set((progress?.signed_docs) || []);

  return (
    <div className="app">
      {/* Sidebar */}
      <aside className="sidebar">
        <div className="brand">
          <div className="brand-mark">C</div>
          <div className="brand-name">convoso</div>
          <span className="brand-sub">HR</span>
        </div>
        <nav className="nav">
          {NAV_GROUPS.map(g => (
            <div className="nav-group" key={g.label}>
              <div className="nav-group-label">{g.label}</div>
              {g.items.map(item => {
                const C = I[item.icon];
                return (
                  <button
                    key={item.id}
                    className={"nav-item" + (page === item.id ? " active" : "")}
                    onClick={() => goto(item.id)}
                  >
                    <C className="ni-icon" size={17}/>
                    <span>{item.label}</span>
                    {item.badge && <span className="ni-badge">{item.badge}</span>}
                    {item.dot && !item.badge && <span className="ni-dot"></span>}
                  </button>
                );
              })}
            </div>
          ))}
          <div className="nav-group">
            <div className="nav-group-label">Help</div>
            <button className="nav-item">
              <I.help className="ni-icon" size={17}/>
              <span>Ask People Ops</span>
            </button>
            <button className="nav-item">
              <I.book className="ni-icon" size={17}/>
              <span>Knowledge base</span>
            </button>
          </div>
        </nav>
        <div className="sidebar-foot">
          <Avatar name={hire.name} size="md"/>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div className="user-name">{hire.name}</div>
            <div className="user-role">
              {employee ? (employee.job_title || PERSONAS[t.persona].role) : PERSONAS[t.persona].role}
            </div>
          </div>
          <button className="icon-btn" style={{ width: 28, height: 28 }} title="Settings"><I.more size={14}/></button>
        </div>
      </aside>

      {/* Main */}
      <div className="main-area">
        <header className="topbar">
          <div className="topbar-search">
            <I.search size={16}/>
            <input placeholder="Search docs, people, meetings…"/>
            <kbd>⌘ K</kbd>
          </div>
          <div className="topbar-actions">
            <button className="btn btn-soft btn-sm">
              <I.sparkle size={13}/> Ask Convoso AI
            </button>
            <button className="icon-btn" title="Notifications">
              <I.bell size={16}/>
              <span className="pill">3</span>
            </button>
            <button className="icon-btn" onClick={() => setTweak("dark", !t.dark)} title="Toggle theme">
              {t.dark ? <I.sun size={16}/> : <I.moon size={16}/>}
            </button>
          </div>
        </header>

        <main className="content" key={page}>
          {page === "dashboard" && (
            <Dashboard
              persona={t.persona}
              progress={progressLevel}
              layout={t.layout}
              onNav={goto}
              hireName={hire}
              employeeId={employeeId}
              completedTasks={new Set(progress?.completed_tasks || [])}
            />
          )}
          {page === "meetings"  && <MeetingsPage  persona={t.persona}/>}
          {page === "documents" && (
            <DocumentsPage
              persona={t.persona}
              employeeId={employeeId}
              savedSignedIds={savedSignedIds}
            />
          )}
          {page === "training"  && (
            <TrainingPage
              persona={t.persona}
              employeeId={employeeId}
              savedTraining={progress?.training || {}}
            />
          )}
          {page === "insurance" && (
            <InsurancePage
              persona={t.persona}
              employeeId={employeeId}
            />
          )}
          {page === "profile"   && <ProfilePage   persona={t.persona} employee={employee}/>}
          {page === "payroll"   && <PayrollPage   persona={t.persona}/>}
          {page === "equipment" && <EquipmentPage persona={t.persona}/>}
        </main>
      </div>

      <TweaksPanel>
        <TweakSection label="Theme"/>
        <TweakColor
          label="Accent"
          value={t.accent}
          options={[{ value: "lime", color: "#84cc16" }, { value: "indigo", color: "#6366f1" }, { value: "coral", color: "#ef6a4d" }, { value: "ocean", color: "#0891b2" }].map(o => o.color)}
          onChange={(v) => {
            const map = { "#84cc16": "lime", "#6366f1": "indigo", "#ef6a4d": "coral", "#0891b2": "ocean" };
            setTweak("accent", map[v] || "lime");
          }}
        />
        <TweakToggle label="Dark mode"  value={t.dark}    onChange={(v) => setTweak("dark", v)}/>
        <TweakRadio  label="Density"    value={t.density} options={["compact","regular"]} onChange={(v) => setTweak("density", v)}/>

        <TweakSection label="Dashboard"/>
        <TweakSelect
          label="Layout"
          value={t.layout}
          options={[
            { value: "timeline",  label: "Timeline by week" },
            { value: "checklist", label: "Checklist by priority" },
            { value: "grid",      label: "Card grid by category" },
          ]}
          onChange={(v) => setTweak("layout", v)}
        />
        {!employeeId && (
          <>
            <TweakSelect
              label="Progress"
              value={t.progress}
              options={[
                { value: "day1",  label: "Day 1 — just started" },
                { value: "week1", label: "Week 1 — mid-onboarding" },
                { value: "done",  label: "Complete" },
              ]}
              onChange={(v) => setTweak("progress", v)}
            />
            <TweakSection label="Persona"/>
            <TweakSelect
              label="New hire role"
              value={t.persona}
              options={[
                { value: "eng",    label: "Software Engineer" },
                { value: "design", label: "Product Designer" },
                { value: "sales",  label: "Account Executive" },
              ]}
              onChange={(v) => setTweak("persona", v)}
            />
          </>
        )}
      </TweaksPanel>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App/>);
