// ─────────────────────────────────────────────────────────────
// PORTAL APP — login, shell, routing, global search, data layer
// ─────────────────────────────────────────────────────────────

// ── Login / Signup / Forgot password ──
function AuthScreen() {
  const { Btn, Input, Field } = window.PUI;
  const [mode, setMode] = React.useState("login"); // login | signup | forgot
  const [email, setEmail] = React.useState("");
  const [pw, setPw] = React.useState("");
  const [name, setName] = React.useState("");
  const [err, setErr] = React.useState("");
  const [info, setInfo] = React.useState("");
  const [busy, setBusy] = React.useState(false);

  const go = async () => {
    setErr(""); setInfo(""); setBusy(true);
    try {
      if (mode === "login") {
        const { error } = await sb.auth.signInWithPassword({ email, password: pw });
        if (error) throw error;
      } else if (mode === "signup") {
        if (!name.trim()) throw new Error("Please enter your full name.");
        const { error } = await sb.auth.signUp({ email, password: pw, options: { data: { full_name: name.trim() } } });
        if (error) throw error;
        setInfo("Account created! If email confirmation is enabled, check your inbox — otherwise sign in now.");
        setMode("login");
      } else {
        // forgot password
        if (!email.trim()) throw new Error("Enter your email address first.");
        const { error } = await sb.auth.resetPasswordForEmail(email.trim(), {
          redirectTo: window.location.origin + window.location.pathname,
        });
        if (error) throw error;
        setInfo("Reset link sent! Check your inbox (and spam) — the link brings you back here to set a new password.");
      }
    } catch (e) { setErr(e.message); }
    setBusy(false);
  };

  const TITLES = { login: "Sign In", signup: "Create Account", forgot: "Send Reset Link" };

  return (
    <div style={{ minHeight: "100vh", display: "flex", alignItems: "center", justifyContent: "center", padding: 20, position: "relative", overflow: "hidden" }}>
      <div style={{ position: "absolute", top: -220, left: "50%", transform: "translateX(-50%)", width: 800, height: 600, background: "radial-gradient(circle, rgba(251,208,40,0.14), transparent 65%)", pointerEvents: "none" }} />
      <div style={{ width: "100%", maxWidth: 410, background: "var(--surface-card)", border: "1px solid var(--border-default)", borderRadius: 20, padding: "44px 38px", position: "relative" }}>
        <div style={{ textAlign: "center", marginBottom: 32 }}>
          <img src="assets/zentro-logo.png" alt="Zentro Visuals" style={{ height: 36 }} />
          <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: "0.18em", textTransform: "uppercase", color: "var(--gold-500)", marginTop: 14 }}>Client & Editor Portal</div>
        </div>
        <div style={{ display: "flex", flexDirection: "column", gap: 15 }}>
          {mode === "forgot" && (
            <p style={{ fontSize: 13, color: "var(--text-secondary)", lineHeight: 1.6, margin: 0 }}>
              Enter your account email and we'll send you a link to set a new password.
            </p>
          )}
          {mode === "signup" && <Field label="Full Name" required><Input value={name} onChange={e => setName(e.target.value)} placeholder="Your full name" /></Field>}
          <Field label="Email" required><Input type="email" value={email} onChange={e => setEmail(e.target.value)} placeholder="you@example.com" /></Field>
          {mode !== "forgot" && (
            <Field label="Password" required>
              <Input type="password" value={pw} onChange={e => setPw(e.target.value)} placeholder="••••••••"
                onKeyDown={e => { if (e.key === "Enter") go(); }} />
            </Field>
          )}
          {mode === "login" && (
            <button onClick={() => { setMode("forgot"); setErr(""); setInfo(""); }} style={{ background: "none", border: "none", color: "var(--gold-400)", fontSize: 12, fontWeight: 700, cursor: "pointer", fontFamily: "var(--font-sans)", alignSelf: "flex-end", padding: 0, marginTop: -6 }}>
              Forgot password?
            </button>
          )}
          {err && <div style={{ fontSize: 13, color: "#E2492E" }}>{err}</div>}
          {info && <div style={{ fontSize: 13, color: "#3FB57A" }}>{info}</div>}
          <Btn fullWidth size="lg" onClick={go} disabled={busy}>{busy ? "Please wait…" : TITLES[mode]}</Btn>
          {mode === "login" && (
            <button onClick={() => { setMode("signup"); setErr(""); setInfo(""); }} style={{ background: "none", border: "none", color: "var(--text-tertiary)", fontSize: 13, cursor: "pointer", fontFamily: "var(--font-sans)" }}>
              New here? Create an account
            </button>
          )}
          {mode !== "login" && (
            <button onClick={() => { setMode("login"); setErr(""); setInfo(""); }} style={{ background: "none", border: "none", color: "var(--text-tertiary)", fontSize: 13, cursor: "pointer", fontFamily: "var(--font-sans)" }}>
              ← Back to sign in
            </button>
          )}
        </div>
      </div>
    </div>
  );
}

// ── Set new password (after clicking the reset email link) ──
function ResetPasswordScreen({ onDone }) {
  const { Btn, Input, Field } = window.PUI;
  const [pw1, setPw1] = React.useState("");
  const [pw2, setPw2] = React.useState("");
  const [err, setErr] = React.useState("");
  const [busy, setBusy] = React.useState(false);

  const save = async () => {
    setErr("");
    if (pw1.length < 6) return setErr("Password must be at least 6 characters.");
    if (pw1 !== pw2) return setErr("Passwords don't match.");
    setBusy(true);
    const { error } = await sb.auth.updateUser({ password: pw1 });
    setBusy(false);
    if (error) return setErr(error.message);
    onDone();
  };

  return (
    <div style={{ minHeight: "100vh", display: "flex", alignItems: "center", justifyContent: "center", padding: 20 }}>
      <div style={{ width: "100%", maxWidth: 410, background: "var(--surface-card)", border: "1px solid var(--border-default)", borderRadius: 20, padding: "44px 38px" }}>
        <div style={{ textAlign: "center", marginBottom: 28 }}>
          <img src="assets/zentro-logo.png" alt="Zentro Visuals" style={{ height: 36 }} />
          <h2 style={{ fontFamily: "var(--font-display)", fontWeight: 900, fontSize: 21, letterSpacing: "-0.02em", marginTop: 18 }}>Set a new password</h2>
        </div>
        <div style={{ display: "flex", flexDirection: "column", gap: 15 }}>
          <Field label="New Password" required><Input type="password" value={pw1} onChange={e => setPw1(e.target.value)} placeholder="••••••••" /></Field>
          <Field label="Confirm New Password" required>
            <Input type="password" value={pw2} onChange={e => setPw2(e.target.value)} placeholder="••••••••"
              onKeyDown={e => { if (e.key === "Enter") save(); }} />
          </Field>
          {err && <div style={{ fontSize: 13, color: "#E2492E" }}>{err}</div>}
          <Btn fullWidth size="lg" onClick={save} disabled={busy}>{busy ? "Saving…" : "Save New Password"}</Btn>
        </div>
      </div>
    </div>
  );
}

// ── Global search ──
function GlobalSearch({ tasks, projects, onOpenTask, onOpenProject }) {
  const [q, setQ] = React.useState("");
  const [open, setOpen] = React.useState(false);
  const results = q.trim().length < 2 ? [] : [
    ...projects.filter(p => p.name.toLowerCase().includes(q.toLowerCase())).slice(0, 4).map(p => ({ kind: "project", id: p.id, label: p.name })),
    ...tasks.filter(t => t.title.toLowerCase().includes(q.toLowerCase())).slice(0, 6).map(t => ({ kind: "task", id: t.id, label: t.title })),
  ];
  return (
    <div style={{ position: "relative", flex: 1, maxWidth: 420 }} className="psearch">
      <input value={q} onChange={e => { setQ(e.target.value); setOpen(true); }} onFocus={() => setOpen(true)}
        placeholder="Search tasks & projects…" style={{
          width: "100%", padding: "10px 14px 10px 38px", borderRadius: 10,
          background: "var(--surface-inset)", border: "1px solid var(--border-default)",
          color: "var(--text-primary)", fontSize: 13, fontFamily: "var(--font-sans)", outline: "none",
        }} />
      <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="var(--text-tertiary)" strokeWidth="2" style={{ position: "absolute", left: 13, top: "50%", transform: "translateY(-50%)" }}><circle cx="11" cy="11" r="8"/><path d="m21 21-4.35-4.35"/></svg>
      {open && results.length > 0 && (
        <React.Fragment>
          <div onClick={() => setOpen(false)} style={{ position: "fixed", inset: 0, zIndex: 300 }} />
          <div style={{ position: "absolute", top: 46, left: 0, right: 0, background: "var(--surface-raised)", border: "1px solid var(--border-default)", borderRadius: 12, zIndex: 301, overflow: "hidden", boxShadow: "0 12px 40px rgba(0,0,0,0.5)" }}>
            {results.map(r => (
              <div key={r.kind + r.id} onClick={() => { setOpen(false); setQ(""); r.kind === "task" ? onOpenTask(r.id) : onOpenProject(r.id); }}
                style={{ display: "flex", gap: 10, alignItems: "center", padding: "11px 14px", cursor: "pointer", borderBottom: "1px solid var(--border-subtle)" }}
                onMouseEnter={(e) => e.currentTarget.style.background = "rgba(255,255,255,0.03)"}
                onMouseLeave={(e) => e.currentTarget.style.background = "transparent"}>
                <span style={{ fontSize: 10, fontWeight: 800, letterSpacing: "0.08em", color: "var(--gold-400)", textTransform: "uppercase", width: 52, flexShrink: 0 }}>{r.kind}</span>
                <span style={{ fontSize: 13, color: "var(--text-secondary)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{r.label}</span>
              </div>
            ))}
          </div>
        </React.Fragment>
      )}
    </div>
  );
}

// ── Main shell ──
function PortalApp() {
  const { session, profile } = window.useAuth();
  const { Spinner } = window.PUI;
  const [view, setView] = React.useState("dashboard");
  const [openTaskId, setOpenTaskId] = React.useState(null);
  const [projectFilter, setProjectFilter] = React.useState("");
  const [mobileNav, setMobileNav] = React.useState(false);
  const [recovery, setRecovery] = React.useState(false);

  React.useEffect(() => {
    if (window.location.hash.includes("type=recovery")) setRecovery(true);
    const { data: sub } = sb.auth.onAuthStateChange((event) => {
      if (event === "PASSWORD_RECOVERY") setRecovery(true);
    });
    return () => sub.subscription.unsubscribe();
  }, []);

  // Data
  const [tasks, setTasks] = React.useState([]);
  const [projects, setProjects] = React.useState([]);
  const [clients, setClients] = React.useState([]);
  const [profiles, setProfiles] = React.useState([]);
  const [projectEditors, setProjectEditors] = React.useState([]);
  const [loaded, setLoaded] = React.useState(false);

  const refresh = React.useCallback(async () => {
    if (!profile) return;
    const [t, p, c, pr, pe] = await Promise.all([
      sb.from("tasks").select("*").order("updated_at", { ascending: false }),
      sb.from("projects").select("*").order("created_at", { ascending: false }),
      sb.from("clients").select("*").order("name"),
      sb.from("profiles").select("*").order("full_name"),
      sb.from("project_editors").select("*"),
    ]);
    setTasks(t.data || []); setProjects(p.data || []); setClients(c.data || []);
    setProfiles(pr.data || []); setProjectEditors(pe.data || []);
    setLoaded(true);
  }, [profile]);

  React.useEffect(() => { refresh(); }, [refresh]);

  // Realtime: refresh task list on changes
  React.useEffect(() => {
    if (!profile) return;
    const ch = sb.channel("tasks-all")
      .on("postgres_changes", { event: "*", schema: "public", table: "tasks" }, () => refresh())
      .subscribe();
    return () => sb.removeChannel(ch);
  }, [profile, refresh]);

  if (session === undefined) return <div style={{ minHeight: "100vh", display: "flex", alignItems: "center", justifyContent: "center" }}><Spinner size={28} /></div>;
  if (!session) return <AuthScreen />;
  if (recovery) return <ResetPasswordScreen onDone={() => { setRecovery(false); window.location.hash = ""; }} />;
  if (!profile || !loaded) return <div style={{ minHeight: "100vh", display: "flex", alignItems: "center", justifyContent: "center" }}><Spinner size={28} /></div>;

  const isAdmin = profile.role === "admin";
  const openProject = (pid) => { setProjectFilter(pid); setView("tasks"); };

  const NAV = [
    { id: "dashboard", label: "Dashboard", icon: <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><rect x="3" y="3" width="7" height="9"/><rect x="14" y="3" width="7" height="5"/><rect x="14" y="12" width="7" height="9"/><rect x="3" y="16" width="7" height="5"/></svg> },
    { id: "projects",  label: "Projects",  icon: <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/></svg> },
    { id: "tasks",     label: "Tasks",     icon: <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M9 11l3 3L22 4"/><path d="M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11"/></svg> },
    ...(isAdmin ? [{ id: "users", label: "Users", icon: <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></svg> }] : []),
  ];

  const navItem = (n) => (
    <div key={n.id} onClick={() => { setView(n.id); if (n.id !== "tasks") setProjectFilter(""); setMobileNav(false); }} style={{
      display: "flex", alignItems: "center", gap: 12, padding: "11px 16px", borderRadius: 11, cursor: "pointer",
      fontSize: 14, fontWeight: 600,
      background: view === n.id ? "rgba(251,208,40,0.1)" : "transparent",
      color: view === n.id ? "var(--gold-400)" : "var(--text-tertiary)",
      transition: "all .15s",
    }}
    onMouseEnter={(e) => { if (view !== n.id) e.currentTarget.style.color = "var(--text-primary)"; }}
    onMouseLeave={(e) => { if (view !== n.id) e.currentTarget.style.color = "var(--text-tertiary)"; }}>
      {n.icon}{n.label}
    </div>
  );

  return (
    <div style={{ display: "flex", minHeight: "100vh" }}>
      {/* Sidebar */}
      <aside className="psidebar" style={{
        width: 232, flexShrink: 0, borderRight: "1px solid var(--border-subtle)",
        padding: "26px 16px", display: "flex", flexDirection: "column", gap: 4,
        position: "sticky", top: 0, height: "100vh", background: "var(--surface-inset)",
      }}>
        <a href="https://zentrovisuals.com" target="_blank" rel="noreferrer" style={{ padding: "0 10px", marginBottom: 26 }}><img src="assets/zentro-logo.png" alt="Zentro" style={{ height: 30 }} /></a>
        {NAV.map(navItem)}
        <div style={{ marginTop: "auto", borderTop: "1px solid var(--border-subtle)", paddingTop: 14 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "8px 10px" }}>
            <window.PUI.Avatar name={profile.full_name || profile.email} url={profile.avatar_url} size={34} />
            <div style={{ minWidth: 0 }}>
              <div style={{ fontSize: 13, fontWeight: 700, color: "var(--text-primary)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{profile.full_name || "—"}</div>
              <div style={{ fontSize: 11, color: "var(--gold-400)", textTransform: "capitalize" }}>{profile.role}</div>
            </div>
          </div>
          <button onClick={() => sb.auth.signOut()} style={{ width: "100%", marginTop: 6, padding: "9px", borderRadius: 9, border: "1px solid var(--border-default)", background: "transparent", color: "var(--text-tertiary)", fontSize: 12, fontWeight: 700, cursor: "pointer", fontFamily: "var(--font-sans)" }}>Sign out</button>
        </div>
      </aside>

      {/* Main */}
      <div style={{ flex: 1, minWidth: 0, display: "flex", flexDirection: "column" }}>
        {/* Topbar */}
        <header style={{
          position: "sticky", top: 0, zIndex: 200, display: "flex", alignItems: "center", gap: 14,
          padding: "14px 26px", background: "rgba(8,8,10,0.85)", backdropFilter: "blur(14px)",
          borderBottom: "1px solid var(--border-subtle)",
        }}>
          <button className="pmobile-toggle" onClick={() => setMobileNav(!mobileNav)} style={{ display: "none", width: 38, height: 38, borderRadius: 9, border: "1px solid var(--border-default)", background: "transparent", color: "var(--text-primary)", cursor: "pointer" }}>☰</button>
          <GlobalSearch tasks={tasks} projects={projects} onOpenTask={setOpenTaskId} onOpenProject={openProject} />
          <div style={{ marginLeft: "auto" }}>
            <window.NotificationBell profile={profile} onOpenTask={setOpenTaskId} />
          </div>
        </header>

        {/* Mobile nav drawer */}
        {mobileNav && (
          <div className="pmobile-nav" style={{ borderBottom: "1px solid var(--border-subtle)", padding: 12, background: "var(--surface-inset)" }}>
            {NAV.map(navItem)}
            <button onClick={() => sb.auth.signOut()} style={{ width: "100%", marginTop: 8, padding: 10, borderRadius: 9, border: "1px solid var(--border-default)", background: "transparent", color: "var(--text-tertiary)", fontSize: 13, fontWeight: 700, cursor: "pointer", fontFamily: "var(--font-sans)" }}>Sign out</button>
          </div>
        )}

        {/* Content */}
        <main style={{ padding: "30px 26px 80px", maxWidth: 1240, width: "100%", margin: "0 auto" }}>
          {view === "dashboard" && <window.Dashboard profile={profile} tasks={tasks} projects={projects} profiles={profiles} onOpenTask={setOpenTaskId} onNav={setView} />}
          {view === "projects"  && <window.Projects profile={profile} projects={projects} clients={clients} profiles={profiles} tasks={tasks} projectEditors={projectEditors} refresh={refresh} onOpenProject={openProject} />}
          {view === "tasks"     && <window.Tasks profile={profile} tasks={tasks} projects={projects} clients={clients} profiles={profiles} projectEditors={projectEditors} refresh={refresh} openTaskId={openTaskId} setOpenTaskId={setOpenTaskId} projectFilter={projectFilter} onClearProjectFilter={() => setProjectFilter("")} />}
          {view === "users" && isAdmin && <window.Users profile={profile} profiles={profiles} clients={clients} refresh={refresh} />}
        </main>
      </div>

      {/* Task detail opened from anywhere except tasks view (tasks view renders its own) */}
      {openTaskId && view !== "tasks" && (
        <window.TaskDetail taskId={openTaskId} profile={profile} projects={projects} profiles={profiles}
          clients={clients} projectEditors={projectEditors} refresh={refresh} onClose={() => setOpenTaskId(null)} />
      )}
    </div>
  );
}

// Mount
function mountPortal() {
  if (!window.PUI || !window.Dashboard || !window.Projects || !window.Tasks || !window.TaskDetail || !window.Users || !window.NotificationBell) {
    return setTimeout(mountPortal, 30);
  }
  ReactDOM.createRoot(document.getElementById("root")).render(<PortalApp />);
}
mountPortal();
