// Shared utilities + small components (sparkline, status pill, icons)

const { useState, useEffect, useRef, useMemo, useCallback } = React;

// ── Sparkline ────────────────────────────────────────────────────
function Sparkline({ data, width = 88, height = 28, color }) {
  if (!data || !data.length || data.every(d => d === 0)) {
    return (
      <svg className="sparkline" viewBox={`0 0 ${width} ${height}`} preserveAspectRatio="none">
        <line x1="0" y1={height-1} x2={width} y2={height-1} stroke="var(--border)" strokeDasharray="2 2" />
      </svg>
    );
  }
  const min = Math.min(...data), max = Math.max(...data);
  const range = (max - min) || 1;
  const step = width / Math.max(1, data.length - 1);
  const points = data.map((v, i) => {
    const x = i * step;
    const y = height - 2 - ((v - min) / range) * (height - 4);
    return [x, y];
  });
  const path = points.map((p, i) => `${i === 0 ? "M" : "L"}${p[0].toFixed(1)},${p[1].toFixed(1)}`).join(" ");
  const area = `${path} L${width},${height} L0,${height} Z`;
  return (
    <svg className="sparkline" viewBox={`0 0 ${width} ${height}`} preserveAspectRatio="none" style={color ? { "--accent": color } : undefined}>
      <path className="area" d={area} />
      <path d={path} />
    </svg>
  );
}

// ── Status pill ──────────────────────────────────────────────────
function StatusPill({ status, t }) {
  return (
    <span className="pill" data-status={status}>
      <span className="dot"></span>{t.dash.status[status]}
    </span>
  );
}

// ── Hook: route ──────────────────────────────────────────────────
function useRoute(initial) {
  const [route, setRoute] = useState(initial);
  const go = useCallback((r) => {
    setRoute(r);
    window.scrollTo({ top: 0, behavior: "instant" });
  }, []);
  return [route, go];
}

// ── Hook: project state (filled during onboarding) ──────────────
const EMPTY_PROJECT = { name: "", company: "", website: "", description: "", sector: "", plan: "Growth" };
function useProject() {
  const [proj, setProj] = useState(EMPTY_PROJECT);
  return [proj, setProj];
}

// ── Glyph icons (svg, monoline) ─────────────────────────────────
const Icon = {
  arrow: (p) => <svg width="14" height="14" viewBox="0 0 14 14" fill="none" {...p}><path d="M2 7h10M8 3l4 4-4 4" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/></svg>,
  check: (p) => <svg width="14" height="14" viewBox="0 0 14 14" fill="none" {...p}><path d="M2.5 7.5l3 3 6-6.5" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/></svg>,
  search: (p) => <svg width="14" height="14" viewBox="0 0 14 14" fill="none" {...p}><circle cx="6.2" cy="6.2" r="4.2" stroke="currentColor" strokeWidth="1.4"/><path d="M9.4 9.4l3.1 3.1" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"/></svg>,
  grid: (p) => <svg width="14" height="14" viewBox="0 0 14 14" fill="none" {...p}><rect x="1.5" y="1.5" width="4.5" height="4.5" stroke="currentColor" strokeWidth="1.3"/><rect x="8" y="1.5" width="4.5" height="4.5" stroke="currentColor" strokeWidth="1.3"/><rect x="1.5" y="8" width="4.5" height="4.5" stroke="currentColor" strokeWidth="1.3"/><rect x="8" y="8" width="4.5" height="4.5" stroke="currentColor" strokeWidth="1.3"/></svg>,
  list: (p) => <svg width="14" height="14" viewBox="0 0 14 14" fill="none" {...p}><path d="M2 3.5h10M2 7h10M2 10.5h10" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round"/></svg>,
  kanban: (p) => <svg width="14" height="14" viewBox="0 0 14 14" fill="none" {...p}><rect x="1.5" y="2" width="3" height="10" stroke="currentColor" strokeWidth="1.3"/><rect x="5.5" y="2" width="3" height="7" stroke="currentColor" strokeWidth="1.3"/><rect x="9.5" y="2" width="3" height="5" stroke="currentColor" strokeWidth="1.3"/></svg>,
  close: (p) => <svg width="14" height="14" viewBox="0 0 14 14" fill="none" {...p}><path d="M3 3l8 8M11 3l-8 8" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"/></svg>,
};

// ── Top nav ──────────────────────────────────────────────────────
function UserMenu({ user, signOut, lang }) {
  const [open, setOpen] = useState(false);
  const ref = React.useRef(null);

  useEffect(() => {
    if (!open) return;
    const onDoc = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener("mousedown", onDoc);
    return () => document.removeEventListener("mousedown", onDoc);
  }, [open]);

  const meta = user.user_metadata || {};
  const displayName = meta.full_name || meta.name || user.email;
  const initial = (displayName || user.email)[0].toUpperCase();
  const avatarUrl = meta.avatar_url || meta.picture;

  return (
    <div ref={ref} style={{ position: "relative" }}>
      <button
        onClick={() => setOpen(o => !o)}
        style={{
          display: "inline-flex", alignItems: "center", gap: 8,
          padding: "4px 10px 4px 4px", borderRadius: 999,
          background: "var(--surface)", border: "1px solid var(--border)",
          color: "var(--text)", cursor: "pointer", fontSize: 13,
          maxWidth: 220,
        }}
      >
        {avatarUrl
          ? <img src={avatarUrl} alt="" width="26" height="26" style={{ borderRadius: "50%", objectFit: "cover" }}/>
          : <span style={{ width: 26, height: 26, borderRadius: "50%", background: "var(--surface-hi)", display: "inline-flex", alignItems: "center", justifyContent: "center", fontSize: 12, fontWeight: 600 }}>{initial}</span>}
        <span style={{ overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", maxWidth: 150 }}>{displayName}</span>
        <svg width="10" height="10" viewBox="0 0 10 6" style={{ opacity: 0.6 }}><path d="M1 1l4 4 4-4" stroke="currentColor" strokeWidth="1.5" fill="none" strokeLinecap="round"/></svg>
      </button>

      {open && (
        <div style={{
          position: "absolute", top: "calc(100% + 6px)", right: 0, minWidth: 240,
          background: "var(--surface)", border: "1px solid var(--border)",
          borderRadius: 12, padding: 6, zIndex: 50,
          boxShadow: "0 18px 40px -20px rgba(0,0,0,.6)",
        }}>
          <div style={{ padding: "8px 10px", borderBottom: "1px solid var(--border-2)" }}>
            <div style={{ fontSize: 13, fontWeight: 600, color: "var(--text)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{displayName}</div>
            {displayName !== user.email && (
              <div style={{ fontSize: 12, color: "var(--muted)", marginTop: 2, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{user.email}</div>
            )}
          </div>
          <button
            onClick={() => { setOpen(false); signOut(); }}
            style={{
              width: "100%", textAlign: "left", padding: "9px 10px",
              borderRadius: 8, background: "transparent", border: "none",
              color: "var(--text)", cursor: "pointer", fontSize: 13,
              marginTop: 4,
            }}
            onMouseEnter={(e) => e.currentTarget.style.background = "var(--surface-2)"}
            onMouseLeave={(e) => e.currentTarget.style.background = "transparent"}
          >
            {lang === "fr" ? "Déconnexion" : "Sign out"}
          </button>
        </div>
      )}
    </div>
  );
}

function TopNav({ t, lang, setLang, route, goto, session, signOut }) {
  const user = session?.user;
  const userMenu = user ? <UserMenu user={user} signOut={signOut} lang={lang}/> : null;

  return (
    <header className="nav">
      <div className="nav-brand" onClick={() => goto(route === "dashboard" || route === "agent" || route === "projects" ? "projects" : "landing")} style={{ cursor: "pointer" }}>
        <span className="dot"></span>
        <span>yourprojects<span style={{ color: "var(--muted)" }}>.ai</span></span>
      </div>
      <div className="nav-right">
        <div className="lang-switch">
          <button className={lang === "fr" ? "on" : ""} onClick={() => setLang("fr")}>FR</button>
          <button className={lang === "en" ? "on" : ""} onClick={() => setLang("en")}>EN</button>
        </div>
        {(route === "landing") && (
          <>
            {user
              ? <button className="nav-link" onClick={() => goto("projects")}>{lang === "fr" ? "Mes projets" : "My projects"}</button>
              : <button className="nav-link" onClick={() => goto("auth")}>{t.nav.login}</button>}
            <button className="btn btn-primary" onClick={() => goto(user ? "onboarding" : "auth")}>{t.nav.start} <Icon.arrow/></button>
            {userMenu}
          </>
        )}
        {(route === "auth") && (
          <button className="nav-link" onClick={() => goto("landing")}>← yourprojects.ai</button>
        )}
        {(route === "onboarding" || route === "pricing") && (
          <>
            <button className="nav-link" onClick={() => goto("projects")}>{lang === "fr" ? "Sauvegarder et quitter" : "Save and exit"}</button>
            {userMenu}
          </>
        )}
        {(route === "projects") && (
          <>
            <button className="btn btn-ghost" onClick={() => goto("pricing")}>{lang === "fr" ? "Plan & facturation" : "Plan & billing"}</button>
            <button className="btn btn-primary" onClick={() => goto("onboarding")}>+ {t.common.new_project}</button>
            {userMenu}
          </>
        )}
        {(route === "dashboard" || route === "agent") && (
          <>
            <button className="nav-link" onClick={() => goto("projects")}>← {lang === "fr" ? "Mes projets" : "My projects"}</button>
            <button className="nav-link" onClick={() => goto("onboarding")}>{t.common.new_project}</button>
            {userMenu}
          </>
        )}
      </div>
    </header>
  );
}

Object.assign(window, { Sparkline, StatusPill, useRoute, useProject, EMPTY_PROJECT, Icon, TopNav });
