function useMobile(bp = 768) {
  const [m, setM] = React.useState(() => window.innerWidth < bp);
  React.useEffect(() => {
    const fn = () => setM(window.innerWidth < bp);
    window.addEventListener("resize", fn, { passive: true });
    return () => window.removeEventListener("resize", fn);
  }, [bp]);
  return m;
}

function Shell({ user, current, onNav, onLogout, onJobChange, jobContext, children, darkMode, onToggleTheme, subscriptionPlan = "free", onUpgrade }) {
  const [showSetup, setShowSetup] = React.useState(false);
  const [userMenuOpen, setUserMenuOpen] = React.useState(false);
  const userMenuRef = React.useRef(null);
  const isMobile = useMobile(768);
  const shellBg = darkMode
    ? "radial-gradient(circle at 18% 12%, rgba(255,255,255,.08), transparent 22%), linear-gradient(180deg, #1d1e22 0%, #15161a 100%)"
    : "radial-gradient(circle at 18% 8%, rgba(255,255,255,.92), transparent 22%), linear-gradient(180deg, #f7f8fa 0%, #eef1f4 100%)";
  const topbarBg = darkMode
    ? "linear-gradient(180deg, rgba(44,47,53,.86) 0%, rgba(28,30,35,.92) 100%)"
    : "linear-gradient(180deg, rgba(255,255,255,.88) 0%, rgba(242,245,248,.94) 100%)";
  const topbarBorder = darkMode ? "rgba(214,218,226,.12)" : "rgba(154,162,176,.14)";
  const topbarSubtle = darkMode ? "rgba(255,255,255,.05)" : "rgba(255,255,255,.58)";
  const topbarAccentBg = darkMode ? "rgba(255,255,255,.08)" : "rgba(255,255,255,.48)";
  const topbarAccentBorder = darkMode ? "rgba(188,194,204,.18)" : "rgba(171,178,189,.20)";
  const topbarAccentText = darkMode ? "#d8dde6" : "#6f7785";

  React.useEffect(() => {
    if (!userMenuOpen) return;
    function handleClick(e) {
      if (userMenuRef.current && !userMenuRef.current.contains(e.target)) {
        setUserMenuOpen(false);
      }
    }
    document.addEventListener("mousedown", handleClick);
    return () => document.removeEventListener("mousedown", handleClick);
  }, [userMenuOpen]);

  const isFree = subscriptionPlan === "free";
  const navItems = [
    { id: "dashboard",  label: "Dashboard",    icon: "layout-dashboard" },
    { id: "mock",       label: "Mock interview",icon: "video" },
    { id: "progress",   label: "Progress",      icon: "trending-up",  pro: true },
    { id: "history",    label: "History",       icon: "bar-chart-3" },
  ];

  return (
    <div style={{ display: "flex", flexDirection: "column", minHeight: "100vh", background: shellBg }}>

      {/* ── Top nav ── */}
      <header style={{
        background: topbarBg,
        backdropFilter: "blur(12px)",
        borderBottom: `1px solid ${topbarBorder}`,
        boxShadow: darkMode ? "0 10px 30px rgba(0,0,0,.20)" : "0 10px 28px rgba(112,122,138,.08)",
        padding: isMobile ? "0 16px" : "0 28px",
        display: "flex", alignItems: "center", gap: isMobile ? 0 : 20,
        height: 56, flexShrink: 0,
        position: "sticky", top: 0, zIndex: 100,
        transition: "background 250ms ease, border-color 250ms ease",
      }}>

        {/* Logo */}
        <button onClick={() => onNav("dashboard")} style={{ display: "flex", alignItems: "center", gap: 8, background: "none", border: "none", cursor: "pointer", flexShrink: 0, padding: 0 }}>
          <img src="../../assets/logo.svg" width="24" height="24" alt="" />
          {!isMobile && <span style={{ font: "400 18px var(--font-sans)", letterSpacing: "-0.03em", color: "var(--fg-1)" }}>greenroom</span>}
        </button>

        {/* Divider — desktop only */}
        {!isMobile && <div style={{ width: 1, height: 22, background: "var(--border-1)", flexShrink: 0 }} />}

        {/* Desktop nav items */}
        {!isMobile && (
          <nav style={{ display: "flex", alignItems: "stretch", justifyContent: "center", gap: 2, flex: 1, height: "100%" }}>
            {navItems.map(it => {
              const active = it.id === current;
              // Payments hidden: never show locked pro nav items to free users.
              const locked = it.pro && isFree && !!onUpgrade;
              return (
                <button key={it.id} onClick={() => locked ? onUpgrade?.("pro") : onNav(it.id)} style={{
                  position: "relative", background: "transparent",
                  color: active ? topbarAccentText : "var(--fg-2)",
                  border: 0, padding: "0 14px", borderRadius: 0,
                  font: `${active ? "600" : "500"} 17px var(--font-sans)`, letterSpacing: "-0.005em",
                  display: "flex", alignItems: "center", gap: 7, cursor: "pointer", transition: "color 140ms",
                }}
                  onMouseEnter={e => { e.currentTarget.style.color = active ? topbarAccentText : "var(--fg-1)"; e.currentTarget.style.background = active ? "transparent" : topbarSubtle; }}
                  onMouseLeave={e => { e.currentTarget.style.color = active ? topbarAccentText : "var(--fg-2)"; e.currentTarget.style.background = "transparent"; }}
                >
                  <Icon name={it.icon} size={16} color={active ? topbarAccentText : "var(--fg-3)"} />
                  {it.label}
                  {locked && (
                    <svg width="12" height="12" viewBox="0 0 12 12" fill="none" style={{ flexShrink: 0, opacity: 0.45 }}>
                      <rect x="2" y="5.5" width="8" height="5.5" rx="1.5" fill="currentColor"/>
                      <path d="M3.5 5.5V3.5a2.5 2.5 0 0 1 5 0v2" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round"/>
                    </svg>
                  )}
                  {active && <span style={{ position: "absolute", left: 0, right: 0, bottom: 0, height: 2, borderRadius: "2px 2px 0 0", background: topbarAccentText }} />}
                </button>
              );
            })}
            {/* Admin link removed from topnav — admin is accessed by visiting /admin directly.
                Backend (_is_admin / ADMIN_EMAILS env) enforces actual access control. */}
          </nav>
        )}

        {/* Mobile: page title */}
        {isMobile && (
          <span style={{ flex: 1, textAlign: "center", font: "600 16px var(--font-sans)", color: "var(--fg-1)", letterSpacing: "-0.02em" }}>
            {navItems.find(it => it.id === current)?.label || "Greenroom"}
          </span>
        )}

        {/* Right: role chip + theme + user */}
        <div style={{ display: "flex", alignItems: "center", gap: isMobile ? 8 : 12, flexShrink: 0 }}>

          {/* Role chip — desktop only */}
          {!isMobile && (jobContext?.role ? (
            <button onClick={() => setShowSetup(true)} style={{
              display: "flex", alignItems: "center", gap: 7,
              padding: "5px 12px 5px 9px", borderRadius: 999, cursor: "pointer",
              background: topbarAccentBg, border: `1px solid ${topbarAccentBorder}`,
              font: "500 15px var(--font-sans)", color: topbarAccentText,
              whiteSpace: "nowrap", maxWidth: 200, overflow: "hidden", textOverflow: "ellipsis",
            }}>
              <div style={{ width: 7, height: 7, borderRadius: 999, background: topbarAccentText, flexShrink: 0 }} />
              {jobContext.role}{jobContext.company ? ` · ${jobContext.company}` : ""}
            </button>
          ) : (
            <button onClick={() => setShowSetup(true)} style={{
              height: 32, padding: "0 12px", borderRadius: 7, cursor: "pointer",
              border: `1px solid ${topbarBorder}`, background: topbarSubtle,
              display: "flex", alignItems: "center", gap: 6,
              font: "500 15px var(--font-sans)", color: "var(--fg-2)",
            }}>
              <Icon name="plus" size={15} color="var(--fg-4)" />
              Set role
            </button>
          ))}

          {/* Theme toggle */}
          <button onClick={onToggleTheme} title={darkMode ? "Switch to light mode" : "Switch to dark mode"} style={{
            width: 34, height: 34, borderRadius: 8, border: "1px solid var(--border-1)",
            background: "transparent", cursor: "pointer",
            display: "flex", alignItems: "center", justifyContent: "center",
            color: "var(--fg-3)", transition: "background 140ms, border-color 140ms, color 140ms",
          }}
            onMouseEnter={e => { e.currentTarget.style.background = "var(--bg-subtle)"; e.currentTarget.style.color = "var(--fg-1)"; }}
            onMouseLeave={e => { e.currentTarget.style.background = "transparent"; e.currentTarget.style.color = "var(--fg-3)"; }}
          >
            <Icon name={darkMode ? "sun" : "moon"} size={16} color="currentColor" />
          </button>

          {/* User avatar + dropdown */}
          <div ref={userMenuRef} style={{ position: "relative" }}>
            <button onClick={() => setUserMenuOpen(v => !v)} style={{
              display: "flex", alignItems: "center", gap: isMobile ? 0 : 8,
              padding: isMobile ? "2px" : "4px 8px 4px 4px", borderRadius: 999, cursor: "pointer",
              border: `1px solid ${userMenuOpen ? topbarAccentBorder : topbarBorder}`,
              background: userMenuOpen ? topbarAccentBg : topbarSubtle,
              transition: "border-color 140ms, background 140ms",
            }}>
              {user.picture
                ? <img src={user.picture} width="30" height="30" style={{ borderRadius: 999, flexShrink: 0, border: "1.5px solid var(--border-1)" }} alt="" />
                : <Avatar initials={user.initials} size={30} brand />}
              {!isMobile && <>
                <span style={{ font: "500 15px var(--font-sans)", color: "var(--fg-1)", whiteSpace: "nowrap", paddingRight: 2 }}>{user.firstName || user.name}</span>
                <Icon name="chevron-down" size={15} color="var(--fg-3)" />
              </>}
            </button>

            {userMenuOpen && (
              <div style={{
                position: "absolute", top: "calc(100% + 8px)", right: 0, zIndex: 200,
                background: darkMode ? "linear-gradient(180deg, #25282e 0%, #1c1f24 100%)" : "linear-gradient(180deg, #ffffff 0%, #f3f5f8 100%)",
                borderRadius: 12, border: `1px solid ${topbarBorder}`,
                boxShadow: darkMode ? "0 12px 32px rgba(0,0,0,0.24)" : "0 12px 32px rgba(112,122,138,.10)",
                overflow: "hidden", minWidth: 200,
              }}>
                <div style={{ padding: "14px 16px 12px", borderBottom: "1px solid var(--border-1)" }}>
                  <div style={{ font: "600 13px var(--font-sans)", color: "var(--fg-1)" }}>{user.name}</div>
                  <div style={{ font: "12px var(--font-sans)", color: "var(--fg-3)", marginTop: 2 }}>{user.email}</div>
                </div>
                <div style={{ padding: "6px" }}>
                  {isMobile && (
                    <button onClick={() => { setShowSetup(true); setUserMenuOpen(false); }} style={{
                      width: "100%", display: "flex", alignItems: "center", gap: 10,
                      padding: "8px 10px", borderRadius: 7, border: "none",
                      background: "transparent", cursor: "pointer",
                      font: "500 13px var(--font-sans)", color: "var(--fg-1)", textAlign: "left",
                    }}>
                      <Icon name="briefcase" size={14} color="var(--fg-3)" />
                      {jobContext?.role || "Set role"}
                    </button>
                  )}
                  <button onClick={() => { onNav("settings"); setUserMenuOpen(false); }} style={{
                    width: "100%", display: "flex", alignItems: "center", gap: 10,
                    padding: "8px 10px", borderRadius: 7, border: "none",
                    background: "transparent", cursor: "pointer",
                    font: "500 13px var(--font-sans)", color: "var(--fg-1)", textAlign: "left",
                    transition: "background 120ms",
                  }}
                    onMouseEnter={e => e.currentTarget.style.background = "var(--bg-subtle)"}
                    onMouseLeave={e => e.currentTarget.style.background = "transparent"}
                  >
                    <Icon name="settings" size={14} color="var(--fg-3)" />
                    Settings
                  </button>
                  <div style={{ height: 1, background: "var(--border-1)", margin: "4px 0" }} />
                  <button onClick={() => { setUserMenuOpen(false); onLogout(); }} style={{
                    width: "100%", display: "flex", alignItems: "center", gap: 10,
                    padding: "8px 10px", borderRadius: 7, border: "none",
                    background: "transparent", cursor: "pointer",
                    font: "500 13px var(--font-sans)", color: "var(--gr-danger, #ef4444)", textAlign: "left",
                    transition: "background 120ms",
                  }}
                    onMouseEnter={e => e.currentTarget.style.background = "rgba(239,68,68,0.05)"}
                    onMouseLeave={e => e.currentTarget.style.background = "transparent"}
                  >
                    <Icon name="log-out" size={14} color="var(--gr-danger, #ef4444)" />
                    Sign out
                  </button>
                </div>
              </div>
            )}
          </div>
        </div>
      </header>

      {/* ── Content ── */}
      <div className="gr-shell-content" style={{ flex: 1, display: "flex", flexDirection: "column", minWidth: 0 }}>
        {children}
      </div>

      {/* ── Mobile bottom tab bar ── */}
      {isMobile && (
        <nav style={{
          position: "fixed", bottom: 0, left: 0, right: 0, height: 60,
          background: topbarBg, backdropFilter: "blur(12px)",
          borderTop: `1px solid ${topbarBorder}`,
          display: "flex", zIndex: 100,
          boxShadow: darkMode ? "0 -4px 20px rgba(0,0,0,.22)" : "0 -4px 16px rgba(112,122,138,.10)",
        }}>
          {navItems.map(it => {
            const active = it.id === current;
            const locked = it.pro && isFree;
            return (
              <button key={it.id} onClick={() => locked ? onUpgrade?.("pro") : onNav(it.id)} style={{
                flex: 1, display: "flex", flexDirection: "column",
                alignItems: "center", justifyContent: "center", gap: 4,
                background: "none", border: "none", cursor: "pointer",
                padding: "8px 0",
                transition: "opacity 140ms",
                position: "relative",
              }}>
                <Icon name={it.icon} size={20} color={active ? "var(--gr-green-500)" : "var(--fg-4)"} />
                {locked && (
                  <svg width="10" height="10" viewBox="0 0 12 12" fill="none" style={{ position: "absolute", top: 5, right: "calc(50% - 15px)", opacity: 0.45 }}>
                    <rect x="2" y="5.5" width="8" height="5.5" rx="1.5" fill="currentColor"/>
                    <path d="M3.5 5.5V3.5a2.5 2.5 0 0 1 5 0v2" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round"/>
                  </svg>
                )}
                <span style={{
                  font: `${active ? "600" : "400"} 10px var(--font-sans)`,
                  color: active ? "var(--gr-green-500)" : "var(--fg-4)",
                  letterSpacing: "0.01em",
                }}>{it.label.split(" ")[0]}</span>
              </button>
            );
          })}
        </nav>
      )}

      {/* Setup panel */}
      {showSetup && (
        <SetupPanel
          initial={jobContext}
          onSave={ctx => { onJobChange(ctx); setShowSetup(false); }}
          onClose={() => setShowSetup(false)}
          darkMode={darkMode}
        />
      )}

      {/* Support & feedback widget — always available */}
      <SupportWidget user={user} darkMode={darkMode} isMobile={isMobile} />
    </div>
  );
}

// ── Support & feedback widget ─────────────────────────────────
// Minimal feedback box: heading, textarea, send button. The user's email
// rides along silently (from their auth session) so we can reply.
function SupportWidget({ user, darkMode, isMobile }) {
  const [open, setOpen]       = React.useState(false);
  const [message, setMessage] = React.useState("");
  const [sending, setSending] = React.useState(false);
  const [sent, setSent]       = React.useState(false);
  const [error, setError]     = React.useState("");
  const panelRef = React.useRef(null);

  React.useEffect(() => {
    if (!open) return;
    const handleClick = e => { if (panelRef.current && !panelRef.current.contains(e.target)) setOpen(false); };
    const handleKey   = e => { if (e.key === "Escape") setOpen(false); };
    document.addEventListener("mousedown", handleClick);
    document.addEventListener("keydown",   handleKey);
    return () => {
      document.removeEventListener("mousedown", handleClick);
      document.removeEventListener("keydown",   handleKey);
    };
  }, [open]);

  async function submit(e) {
    e.preventDefault();
    if (message.trim().length < 3) { setError("Please write a bit more."); return; }
    setSending(true); setError("");
    try {
      const res = await fetch("https://api.usegreenroom.app/api/contact", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          type:    "feedback",
          message: message.trim(),
          email:   user?.email || null,
          name:    user?.name  || null,
        }),
      });
      if (!res.ok) throw new Error();
      setSent(true);
      window.posthog?.capture('feedback_submitted');
      setTimeout(() => { setOpen(false); setSent(false); setMessage(""); }, 1800);
    } catch {
      setError("Couldn't send. Try again.");
    }
    setSending(false);
  }

  const surface   = darkMode ? "#1e1f23" : "#ffffff";
  const surface2  = darkMode ? "#25282e" : "#f6f7f9";
  const border    = darkMode ? "rgba(214,218,226,.12)" : "rgba(154,162,176,.18)";
  const fg1       = darkMode ? "#e8ebf0" : "#1a1b1f";
  const fg3       = darkMode ? "#8a90a0" : "#6f7785";
  const inputBg   = darkMode ? "#2a2d34" : "#fafbfc";
  const fabBottom = isMobile ? 76 : 24;

  return (
    <>
      {!open && (
        <button
          onClick={() => setOpen(true)}
          aria-label="Feedback"
          style={{
            position: "fixed", right: 24, bottom: fabBottom, zIndex: 250,
            width: 52, height: 52, borderRadius: 999, border: "none", cursor: "pointer",
            background: "var(--gr-green-500, #1F7A4F)", color: "#fff",
            boxShadow: "0 8px 24px rgba(31,122,79,.32), 0 2px 6px rgba(0,0,0,.12)",
            display: "flex", alignItems: "center", justifyContent: "center",
            transition: "transform 160ms cubic-bezier(.16,1,.3,1)",
          }}
          onMouseEnter={e => e.currentTarget.style.transform = "translateY(-2px)"}
          onMouseLeave={e => e.currentTarget.style.transform = "none"}
        >
          <Icon name="message-circle" size={22} color="#fff" />
        </button>
      )}

      {open && (
        <div
          ref={panelRef}
          style={{
            position: "fixed", right: isMobile ? 12 : 24, bottom: fabBottom,
            width: isMobile ? "calc(100vw - 24px)" : 340, maxWidth: 400, zIndex: 250,
            background: surface, border: `1px solid ${border}`, borderRadius: 14,
            boxShadow: "0 20px 50px rgba(20,20,15,.18)",
            display: "flex", flexDirection: "column", overflow: "hidden",
            animation: "fadeUp 200ms cubic-bezier(.16,1,.3,1)",
          }}
        >
          <style>{`@keyframes fadeUp { from { opacity: 0; transform: translateY(8px); } to { opacity: 1; transform: none; } }`}</style>

          <div style={{ padding: "14px 16px", display: "flex", alignItems: "center", justifyContent: "space-between" }}>
            <div style={{ font: "600 14px var(--font-sans)", color: fg1 }}>Feedback</div>
            <button
              onClick={() => { setOpen(false); setMessage(""); setError(""); setSent(false); }}
              aria-label="Close"
              style={{ background: "none", border: "none", cursor: "pointer", color: fg3, width: 24, height: 24, borderRadius: 6, display: "flex", alignItems: "center", justifyContent: "center" }}
              onMouseEnter={e => e.currentTarget.style.background = surface2}
              onMouseLeave={e => e.currentTarget.style.background = "transparent"}
            >
              <Icon name="x" size={15} />
            </button>
          </div>

          <div style={{ padding: "0 16px 16px" }}>
            {sent ? (
              <div style={{ padding: "16px 0 8px", textAlign: "center" }}>
                <div style={{ width: 36, height: 36, borderRadius: 999, background: "rgba(31,122,79,.12)", margin: "0 auto 10px", display: "flex", alignItems: "center", justifyContent: "center" }}>
                  <Icon name="check" size={18} color="var(--gr-green-500, #1F7A4F)" />
                </div>
                <div style={{ font: "500 14px var(--font-sans)", color: fg1 }}>Thanks — we got it.</div>
              </div>
            ) : (
              <form onSubmit={submit} style={{ display: "flex", flexDirection: "column", gap: 10 }}>
                <textarea
                  value={message}
                  onChange={e => setMessage(e.target.value)}
                  placeholder="What's on your mind?"
                  rows={4}
                  autoFocus
                  style={{
                    width: "100%", padding: "10px 12px", boxSizing: "border-box",
                    border: `1px solid ${border}`, borderRadius: 8, background: inputBg,
                    font: "13px/1.55 var(--font-sans)", color: fg1,
                    outline: "none", resize: "vertical",
                  }}
                />
                {error && (
                  <div style={{ font: "12px var(--font-sans)", color: "#B42318" }}>{error}</div>
                )}
                <button type="submit" disabled={sending} style={{
                  height: 36, borderRadius: 8, border: "none",
                  background: sending ? fg3 : "#14140F", color: "#fff",
                  font: "600 13px var(--font-sans)", letterSpacing: "-0.01em",
                  cursor: sending ? "not-allowed" : "pointer",
                }}>
                  {sending ? "Sending…" : "Send"}
                </button>
              </form>
            )}
          </div>
        </div>
      )}
    </>
  );
}

function SetupPanel({ initial = {}, onSave, onClose, darkMode = false }) {
  const [role, setRole] = React.useState(initial.role || "");
  const [company, setCompany] = React.useState(initial.company || "");
  const [github, setGithub] = React.useState(initial.github || "");
  const [ghStatus, setGhStatus] = React.useState(null);

  // LinkedIn rich state
  const [liData, setLiData] = React.useState(
    initial.linkedinName ? { name: initial.linkedinName, first_name: initial.linkedinFirstName, headline: initial.linkedinHeadline, bio: initial.linkedinBio, experiences: initial.linkedinExperiences || [], skills: initial.linkedinSkills || [], posts: initial.linkedinPosts || [], picture: initial.linkedinPicture } : null
  );
  const [liLoading, setLiLoading] = React.useState(false);
  const [liError, setLiError] = React.useState("");
  const [jobDesc, setJobDesc] = React.useState(initial.jobDescription || "");

  async function handleLinkedInFile(e) {
    const file = e.target.files?.[0];
    if (!file) return;
    const ext = file.name.split(".").pop().toLowerCase();
    if (!["zip", "csv", "json"].includes(ext)) { setLiError("Please upload your LinkedIn data export (.zip, .csv, or .json)."); e.target.value = ""; return; }
    if (file.size > 20 * 1024 * 1024) { setLiError("File is too large (max 20 MB)."); e.target.value = ""; return; }
    setLiLoading(true); setLiError("");
    try {
      const token = localStorage.getItem("gr.token") || "";
      const formData = new FormData();
      formData.append("file", file);
      const res = await fetch("https://api.usegreenroom.app/api/linkedin/import", {
        method: "POST",
        headers: { Authorization: `Bearer ${token}` },
        body: formData,
      });
      const data = await res.json();
      if (data.error) { setLiError(data.error); }
      else { setLiData(data); }
    } catch {
      setLiError("Could not reach the server. Make sure the backend is running.");
    }
    setLiLoading(false);
    e.target.value = "";
  }

  async function verifyGithub() {
    if (!github.trim()) return;
    const username = github.trim().replace(/.*github\.com\//, "").replace(/\/$/, "");
    setGhStatus("loading");
    try {
      const res = await fetch(`https://api.github.com/users/${username}`);
      if (res.ok) {
        const data = await res.json().catch(() => null);
        if (!data) { setGhStatus("error"); return; }
        setGithub(username);
        setGhStatus({ name: data.name || username, repos: data.public_repos, avatar: data.avatar_url });
      } else { setGhStatus("error"); }
    } catch { setGhStatus("error"); }
  }

  function save() {
    onSave({
      role, company,
      jobDescription: jobDesc,
      github: typeof ghStatus === "object" ? github : (initial.github || ""),
      linkedinName: liData?.name || initial.linkedinName || "",
      linkedinFirstName: liData?.first_name || initial.linkedinFirstName || "",
      linkedinLastName: liData?.last_name || initial.linkedinLastName || "",
      linkedinHeadline: liData?.headline || initial.linkedinHeadline || "",
      linkedinBio: liData?.bio || initial.linkedinBio || "",
      linkedinExperiences: liData?.experiences || initial.linkedinExperiences || [],
      linkedinSkills: liData?.skills || initial.linkedinSkills || [],
      linkedinPosts: liData?.posts || initial.linkedinPosts || [],
      linkedinPicture: liData?.picture || initial.linkedinPicture || "",
      linkedinEmail: initial.linkedinEmail || "",
      linkedinId: initial.linkedinId || "",
    });
  }

  const inputStyle = { flex: 1, height: 38, padding: "0 12px", boxSizing: "border-box", border: "1px solid var(--border-1)", borderRadius: 7, font: "var(--text-body)", outline: "none", color: "var(--fg-1)", background: "var(--bg-subtle)" };
  const labelStyle = { font: "500 13px var(--font-sans)", color: "var(--fg-1)", marginBottom: 4 };

  return (
    <div style={{ position: "fixed", inset: 0, zIndex: 300, display: "flex" }}>
      <div onClick={onClose} style={{ position: "absolute", inset: 0, background: "rgba(0,0,0,0.45)", backdropFilter: "blur(2px)" }} />
      <div style={{
        position: "absolute", right: 0, top: 0, bottom: 0, width: 460,
        background: darkMode ? "#1e1f23" : "#ffffff", borderLeft: "1px solid var(--border-1)",
        display: "flex", flexDirection: "column", overflow: "hidden",
        boxShadow: "-20px 0 60px rgba(0,0,0,0.12)",
      }}>
        {/* Header */}
        <div style={{ padding: "22px 24px 18px", borderBottom: "1px solid var(--border-1)", display: "flex", alignItems: "center", justifyContent: "space-between", flexShrink: 0 }}>
          <div>
            <div style={{ font: "400 20px/1 var(--font-display)", letterSpacing: "-0.02em" }}>Interview setup</div>
            <div style={{ font: "13px var(--font-sans)", color: "var(--fg-3)", marginTop: 3 }}>Tell Ari what you're preparing for</div>
          </div>
          <button onClick={onClose} style={{ background: "none", border: "none", cursor: "pointer", color: "var(--fg-4)", display: "flex", padding: 4 }}>
            <Icon name="x" size={18} />
          </button>
        </div>

        <div style={{ flex: 1, overflowY: "auto", padding: 24, display: "flex", flexDirection: "column", gap: 28 }}>

          {/* Job details */}
          <div>
            <div style={labelStyle}>Job details</div>
            <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
              <TextField label="Target role" placeholder="e.g. Software Engineer" value={role} onChange={e => setRole(e.target.value)} />
              <TextField label="Company" placeholder="e.g. Google" value={company} onChange={e => setCompany(e.target.value)} />
              <div>
                <div style={{ font: "500 13px var(--font-sans)", color: "var(--fg-1)", marginBottom: 6 }}>
                  Job description
                  <span style={{ font: "400 12px var(--font-sans)", color: "var(--fg-4)", marginLeft: 8 }}>optional but highly recommended</span>
                </div>
                <textarea
                  value={jobDesc}
                  onChange={e => setJobDesc(e.target.value)}
                  placeholder={"Paste the full job description from the company's careers page.\n\nAri will read the required skills, responsibilities, and seniority level to ask questions that match exactly what this role is looking for."}
                  rows={7}
                  style={{
                    width: "100%", padding: "10px 12px", boxSizing: "border-box",
                    border: "1px solid var(--border-1)", borderRadius: 8,
                    font: "13px var(--font-sans)", color: "var(--fg-1)",
                    outline: "none", resize: "vertical", background: "var(--bg-subtle)", lineHeight: 1.65,
                    transition: "border-color 150ms",
                  }}
                  onFocus={e => e.target.style.borderColor = "var(--border-focus)"}
                  onBlur={e => e.target.style.borderColor = "var(--border-1)"}
                />
                {jobDesc.length > 50 && (
                  <div style={{ display: "flex", alignItems: "center", gap: 6, marginTop: 6, font: "12px var(--font-sans)", color: "var(--gr-green-600)" }}>
                    <Icon name="check-circle-2" size={13} color="var(--gr-green-500)" />
                    {jobDesc.split(/\s+/).filter(Boolean).length} words — Ari will use this to tailor every question
                  </div>
                )}
              </div>
            </div>
          </div>

          {/* LinkedIn */}
          <div>
            <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 4 }}>
              <svg width="14" height="14" viewBox="0 0 24 24" fill="#0077b5"><path d="M20.45 20.45h-3.55v-5.57c0-1.33-.02-3.04-1.85-3.04-1.85 0-2.13 1.45-2.13 2.94v5.67H9.36V9h3.41v1.56h.05c.48-.9 1.64-1.85 3.37-1.85 3.6 0 4.27 2.37 4.27 5.46v6.28ZM5.34 7.43a2.06 2.06 0 1 1 0-4.12 2.06 2.06 0 0 1 0 4.12ZM7.12 20.45H3.56V9h3.56v11.45ZM22.22 0H1.77C.79 0 0 .77 0 1.72v20.56C0 23.23.79 24 1.77 24h20.45C23.21 24 24 23.23 24 22.28V1.72C24 .77 23.21 0 22.22 0Z" /></svg>
              <span style={labelStyle}>LinkedIn data export</span>
            </div>

            {/* How-to instructions */}
            <div style={{ padding: "10px 12px", borderRadius: 8, background: "var(--bg-subtle)", border: "1px solid var(--border-1)", marginBottom: 14 }}>
              <div style={{ font: "600 12px var(--font-sans)", color: "var(--fg-1)", marginBottom: 6 }}>How to export your LinkedIn data</div>
              {[
                "Go to linkedin.com → Me → Settings & Privacy",
                'Data privacy → "Get a copy of your data"',
                'Select "The works" and click Request archive',
                "Download the ZIP when LinkedIn emails you (≈10 min)",
                "Upload it below — we parse it locally, never store raw files",
              ].map((step, i) => (
                <div key={i} style={{ display: "flex", gap: 8, marginBottom: 3 }}>
                  <span style={{ font: "700 11px var(--font-mono)", color: "var(--gr-green-600)", flexShrink: 0, minWidth: 14 }}>{i + 1}.</span>
                  <span style={{ font: "12px var(--font-sans)", color: "var(--fg-2)", lineHeight: 1.5 }}>{step}</span>
                </div>
              ))}
            </div>

            {/* File upload */}
            <label style={{ display: "block", marginBottom: 10, cursor: "pointer" }}>
              <div style={{
                border: `2px dashed ${liLoading ? "var(--gr-green-300)" : "var(--border-1)"}`,
                borderRadius: 9, padding: "18px 16px", textAlign: "center",
                background: liLoading ? "var(--bg-brand-soft)" : "var(--bg-subtle)",
                transition: "all 150ms",
              }}>
                {liLoading ? (
                  <div style={{ display: "flex", alignItems: "center", justifyContent: "center", gap: 8, color: "var(--gr-green-600)" }}>
                    <div style={{ width: 14, height: 14, borderRadius: 999, border: "2px solid var(--gr-green-200)", borderTopColor: "var(--gr-green-500)", animation: "spin 700ms linear infinite" }} />
                    <span style={{ font: "500 13px var(--font-sans)" }}>Parsing your LinkedIn data…</span>
                  </div>
                ) : (
                  <>
                    <Icon name="upload" size={18} color="var(--fg-3)" />
                    <div style={{ font: "500 13px var(--font-sans)", color: "var(--fg-1)", marginTop: 6 }}>Upload LinkedIn export</div>
                    <div style={{ font: "12px var(--font-sans)", color: "var(--fg-3)", marginTop: 2 }}>Drop your .zip file here or click to browse</div>
                  </>
                )}
              </div>
              <input type="file" accept=".zip,.csv" onChange={handleLinkedInFile} style={{ display: "none" }} />
            </label>

            {liError && (
              <div style={{ font: "13px var(--font-sans)", color: "var(--gr-danger)", marginBottom: 10, padding: "8px 12px", background: "rgba(239,68,68,0.05)", borderRadius: 7, border: "1px solid rgba(239,68,68,0.15)" }}>
                {liError}
              </div>
            )}

            {/* Parsed profile preview */}
            {liData?.name && (
              <div style={{ marginBottom: 14, padding: "12px 14px", borderRadius: 10, background: "rgba(0,119,181,0.04)", border: "1px solid rgba(0,119,181,0.15)" }}>
                <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 8 }}>
                  <div style={{ width: 34, height: 34, borderRadius: 999, background: "#0077b5", display: "flex", alignItems: "center", justifyContent: "center", color: "#fff", font: "700 12px var(--font-sans)", flexShrink: 0 }}>in</div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ font: "600 14px var(--font-sans)", color: "var(--fg-1)" }}>{liData.name}</div>
                    {liData.headline && <div style={{ font: "12px var(--font-sans)", color: "#0077b5", marginTop: 1 }}>{liData.headline}</div>}
                  </div>
                  <Icon name="check-circle-2" size={16} color="var(--gr-green-500)" />
                </div>
                <div style={{ display: "flex", flexWrap: "wrap", gap: 6 }}>
                  {liData.experiences?.length > 0 && <span style={{ font: "11px var(--font-sans)", color: "var(--fg-3)", background: "var(--bg-subtle)", padding: "2px 8px", borderRadius: 4 }}>{liData.experiences.length} roles imported</span>}
                  {liData.skills?.length > 0 && <span style={{ font: "11px var(--font-sans)", color: "var(--fg-3)", background: "var(--bg-subtle)", padding: "2px 8px", borderRadius: 4 }}>{liData.skills.length} skills</span>}
                  {liData.posts?.length > 0 && <span style={{ font: "11px var(--font-sans)", color: "var(--fg-3)", background: "var(--bg-subtle)", padding: "2px 8px", borderRadius: 4 }}>{liData.posts.length} posts</span>}
                  {liData.bio && <span style={{ font: "11px var(--font-sans)", color: "var(--fg-3)", background: "var(--bg-subtle)", padding: "2px 8px", borderRadius: 4 }}>Bio ✓</span>}
                </div>
              </div>
            )}

          </div>

          {/* GitHub */}
          <div>
            <div style={labelStyle}>GitHub</div>
            <div style={{ font: "13px var(--font-sans)", color: "var(--fg-3)", marginBottom: 10 }}>Ari references your top repos when asking technical questions</div>
            <div style={{ display: "flex", gap: 8 }}>
              <input placeholder="username or profile URL" value={github}
                onChange={e => { setGithub(e.target.value); setGhStatus(null); }}
                style={inputStyle}
              />
              <button onClick={verifyGithub} style={{ height: 38, padding: "0 14px", borderRadius: 7, border: "1px solid var(--border-1)", background: "var(--bg-subtle)", color: "var(--fg-1)", font: "500 13px var(--font-sans)", cursor: "pointer", whiteSpace: "nowrap" }}>Connect</button>
            </div>
            {ghStatus === "loading" && <div style={{ font: "13px var(--font-sans)", color: "var(--fg-3)", marginTop: 8 }}>Verifying…</div>}
            {ghStatus === "error" && <div style={{ font: "13px var(--font-sans)", color: "var(--gr-danger)", marginTop: 8 }}>Username not found</div>}
            {typeof ghStatus === "object" && ghStatus !== null && (
              <div style={{ marginTop: 10, display: "flex", alignItems: "center", gap: 10, padding: "10px 12px", borderRadius: 8, background: "var(--bg-subtle)", border: "1px solid var(--border-1)" }}>
                <img src={ghStatus.avatar} width="28" height="28" style={{ borderRadius: 999 }} alt="" />
                <div>
                  <div style={{ font: "500 13px var(--font-sans)" }}>{ghStatus.name}</div>
                  <div style={{ font: "12px var(--font-sans)", color: "var(--fg-3)" }}>{ghStatus.repos} public repos</div>
                </div>
                <Icon name="check-circle-2" size={16} color="var(--gr-green-500)" style={{ marginLeft: "auto" }} />
              </div>
            )}
          </div>

        </div>

        <div style={{ padding: "16px 24px", borderTop: "1px solid var(--border-1)", display: "flex", justifyContent: "flex-end", gap: 10, flexShrink: 0 }}>
          <Button variant="secondary" onClick={onClose}>Cancel</Button>
          <Button variant="primary" onClick={save} disabled={!role}>Save changes</Button>
        </div>
      </div>
    </div>
  );
}

window.Shell = Shell;
