// shell.jsx — site nav, footer, layout primitives shared across all routes

const ROUTES = [
{ path: "/", label: "Home" },
{ path: "/goal", label: "Get started" },
{ path: "/dashboard", label: "Dashboard" }];


function useHashRoute() {
  const [hash, setHash] = React.useState(() => window.location.hash.slice(1) || "/");
  React.useEffect(() => {
    const onHash = () => setHash(window.location.hash.slice(1) || "/");
    window.addEventListener("hashchange", onHash);
    return () => window.removeEventListener("hashchange", onHash);
  }, []);
  const navigate = React.useCallback((to) => {
    window.location.hash = to;
    window.scrollTo({ top: 0, behavior: "instant" });
  }, []);
  return [hash, navigate];
}

function NavLink({ to, children, current, onClick }) {
  return (
    <a
      href={`#${to}`}
      onClick={onClick}
      style={{
        fontFamily: "var(--font-mono)",
        fontSize: 12,
        letterSpacing: "0.08em",
        textTransform: "uppercase",
        color: current ? "var(--ink)" : "var(--ink-3)",
        padding: "8px 0",
        position: "relative",
        transition: "color 160ms ease"
      }}
      onMouseEnter={(e) => e.currentTarget.style.color = "var(--ink)"}
      onMouseLeave={(e) => e.currentTarget.style.color = current ? "var(--ink)" : "var(--ink-3)"}>
      
      {children}
    </a>);

}

function sessionDisplayName(session) {
  const user = session && session.user;
  if (!user) return "";
  return user.name || (user.email ? user.email.split("@")[0] : "");
}

function useBackendSession() {
  const [session, setSession] = React.useState(() => (
    window.FolioBackendSession || (window.FolioBackend && window.FolioBackend.state && window.FolioBackend.state.session) || null
  ));

  React.useEffect(() => {
    let active = true;
    const apply = (next) => {
      if (active) setSession(next || { authenticated: false, user: null });
    };
    const onSession = (event) => apply(event.detail);
    window.addEventListener("folio:session", onSession);

    if (window.FolioBackend && window.FolioBackend.getSession) {
      window.FolioBackend.getSession()
        .then(apply)
        .catch(() => apply({ authenticated: false, user: null }));
    }

    return () => {
      active = false;
      window.removeEventListener("folio:session", onSession);
    };
  }, []);

  return session;
}

function signInHref(next) {
  return "/signin?next=" + encodeURIComponent(next || "/#/goal");
}

function SiteHeader({ current = "/", minimal = false }) {
  const session = useBackendSession();
  const signedIn = !!(session && session.authenticated);
  const displayName = sessionDisplayName(session);
  const currentNext = window.location.pathname + (window.location.hash || "#/goal");
  return (
    <header style={{
      position: "sticky",
      top: 0,
      zIndex: 50,
      background: "color-mix(in oklch, var(--paper) 88%, transparent)",
      backdropFilter: "blur(12px) saturate(140%)",
      borderBottom: "0.5px solid var(--rule)"
    }}>
      <div className="container" style={{
        display: "flex",
        alignItems: "center",
        justifyContent: "space-between",
        height: 64
      }}>
        <a href="#/" style={{ display: "flex", alignItems: "center", gap: 10 }}>
          <FolioMark />
          <span style={{
            fontFamily: "var(--font-serif)",
            fontSize: 22,
            letterSpacing: "-0.02em",
            color: "var(--ink)"
          }}>Folio</span>
          <span style={{
            fontFamily: "var(--font-mono)",
            fontSize: 10,
            letterSpacing: "0.08em",
            color: "var(--ink-3)",
            textTransform: "uppercase",
            marginLeft: 4,
            padding: "2px 6px",
            border: "0.5px solid var(--rule-2)",
            borderRadius: 4
          }}></span>
        </a>

        {!minimal &&
        <nav style={{ display: "flex", gap: 32, alignItems: "center" }}>
            <NavLink to="/" current={current === "/"}>Overview</NavLink>
            <NavLink to="/#how" current={false}>How it works</NavLink>
            <NavLink to="/#templates" current={false}>Designs</NavLink>
            <NavLink to="/#pricing" current={false}>Pricing</NavLink>
            <NavLink to="/dashboard" current={current === "/dashboard"}>Dashboard</NavLink>
          </nav>
        }

        <div style={{ display: "flex", gap: 10, alignItems: "center" }}>
          {signedIn ? (
            <a href="#/dashboard" style={{ fontFamily: "var(--font-mono)", fontSize: 12, letterSpacing: "0.08em", textTransform: "uppercase", color: "var(--ink-3)", maxWidth: 180, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
              {displayName || "Account"}
            </a>
          ) : (
            <a href={signInHref(currentNext)} style={{ fontFamily: "var(--font-mono)", fontSize: 12, letterSpacing: "0.08em", textTransform: "uppercase", color: "var(--ink-3)" }}>Sign in</a>
          )}
          <a href={signedIn ? "#/goal" : signInHref("/#/goal")} className="btn btn-primary" style={{ padding: "10px 18px", fontSize: 13 }}>
            Build my portfolio <span className="arr">→</span>
          </a>
        </div>
      </div>
    </header>);

}

function FolioMark({ size = 28 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 32 32" fill="none">
      <rect x="4" y="6" width="24" height="22" rx="2" stroke="currentColor" strokeWidth="1.25" />
      <path d="M10 12h12M10 17h8M10 22h6" stroke="currentColor" strokeWidth="1.25" strokeLinecap="round" />
      <circle cx="24" cy="8" r="3" fill="oklch(0.62 0.14 40)" />
    </svg>);

}

function SiteFooter() {
  return (
    <footer style={{
      borderTop: "0.5px solid var(--rule)",
      marginTop: "var(--space-9)",
      padding: "var(--space-7) 0 var(--space-6)"
    }}>
      <div className="container">
        <div style={{ display: "grid", gridTemplateColumns: "2fr 1fr 1fr 1fr", gap: 48, marginBottom: 56 }}>
          <div>
            <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 16, color: "var(--ink)" }}>
              <FolioMark />
              <span style={{ fontFamily: "var(--font-serif)", fontSize: 22 }}>Folio</span>
            </div>
            <p style={{ color: "var(--ink-3)", maxWidth: 360, lineHeight: 1.5, fontSize: 14 }}>
              The portfolio you don't build. Connect your work, approve a draft,
              go live on a real domain — usually under ten minutes.
            </p>
          </div>
          <FooterCol title="Product" items={["How it works", "Designs", "Domains", "Pricing", "Changelog"]} />
          <FooterCol title="Company" items={["About", "Manifesto", "Press", "Careers", "Contact"]} />
          <FooterCol title="Resources" items={["Help", "Status", "Privacy", "Terms", "Security"]} />
        </div>
        <div style={{
          display: "flex",
          justifyContent: "space-between",
          alignItems: "center",
          paddingTop: 24,
          borderTop: "0.5px solid var(--rule)"
        }}>
          <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, letterSpacing: "0.04em", color: "var(--ink-4)" }}>
            © 2026 FOLIO STUDIOS, INC. — BROOKLYN, NEW YORK
          </div>
          <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, letterSpacing: "0.04em", color: "var(--ink-4)" }}>
            v0.6.2 · LAST DEPLOY 11 MIN AGO
          </div>
        </div>
      </div>
    </footer>);

}

function FooterCol({ title, items }) {
  return (
    <div>
      <div className="eyebrow" style={{ marginBottom: 16 }}>{title}</div>
      <ul style={{ listStyle: "none", padding: 0, margin: 0, display: "flex", flexDirection: "column", gap: 10 }}>
        {items.map((it) =>
        <li key={it}>
            <a href="#/" style={{ color: "var(--ink-2)", fontSize: 14 }}>{it}</a>
          </li>
        )}
      </ul>
    </div>);

}

// Step layout — used by every flow screen
function StepLayout({ stepNum, stepLabel, eyebrow, title, sub, children, leftRail = null, footer = null }) {
  return (
    <div style={{ minHeight: "calc(100vh - 64px)", display: "flex", flexDirection: "column" }}>
      <FlowProgress current={stepNum} />
      <div className="container" style={{ padding: "var(--space-8) var(--space-6) var(--space-7)", flex: 1 }}>
        <div style={{ display: "grid", gridTemplateColumns: leftRail ? "240px 1fr" : "1fr", gap: 64 }}>
          {leftRail}
          <div>
            <div className="eyebrow" style={{ marginBottom: 14, color: "var(--accent)" }}>
              <span style={{ fontFamily: "var(--font-serif)", fontSize: 13, letterSpacing: 0, fontStyle: "italic", color: "var(--ink-3)" }}>step</span>
              {" "}{stepNum} — {eyebrow}
            </div>
            <h1 style={{ fontSize: "clamp(40px, 5.2vw, 72px)", marginBottom: 16, maxWidth: "16ch" }}>{title}</h1>
            {sub && <p style={{ fontSize: 18, color: "var(--ink-2)", maxWidth: "60ch", lineHeight: 1.5, marginBottom: 48, fontFamily: "var(--font-serif)", fontStyle: "italic" }}>{sub}</p>}
            {children}
          </div>
        </div>
      </div>
      {footer}
    </div>);

}

function FlowProgress({ current }) {
  const steps = window.STEPS.filter((s) => s.id !== "landing");
  const currentIdx = steps.findIndex((s) => s.num === current);
  return (
    <div style={{
      borderBottom: "0.5px solid var(--rule)",
      background: "var(--paper)",
      padding: "16px 0"
    }}>
      <div className="container" style={{ display: "flex", alignItems: "center", gap: 18, fontFamily: "var(--font-mono)", fontSize: 11, letterSpacing: "0.06em" }}>
        {steps.map((s, i) => {
          const done = i < currentIdx;
          const active = i === currentIdx;
          return (
            <React.Fragment key={s.id}>
              <a
                href={`#${s.path}`}
                onClick={(e) => {if (i > currentIdx) e.preventDefault();}}
                style={{
                  display: "flex",
                  alignItems: "center",
                  gap: 6,
                  color: active ? "var(--ink)" : done ? "var(--ink-3)" : "var(--ink-4)",
                  cursor: i > currentIdx ? "default" : "pointer",
                  transition: "color 140ms"
                }}>
                
                <span style={{
                  width: 18, height: 18,
                  borderRadius: 9,
                  border: "0.5px solid",
                  borderColor: active ? "var(--ink)" : done ? "var(--accent)" : "var(--rule-2)",
                  background: done ? "var(--accent)" : "transparent",
                  color: done ? "var(--paper)" : "currentColor",
                  display: "inline-flex",
                  alignItems: "center",
                  justifyContent: "center",
                  fontSize: 9
                }}>
                  {done ? "✓" : s.num}
                </span>
                <span style={{ textTransform: "uppercase" }}>{s.label}</span>
              </a>
              {i < steps.length - 1 && <span style={{ color: "var(--ink-4)", flex: "0 0 auto" }}>·</span>}
            </React.Fragment>);

        })}
      </div>
    </div>);

}

// Persistent flow state stored on window for cross-page persistence
const FlowStore = {
  state: (() => {
    try {return JSON.parse(sessionStorage.getItem("folio-flow") || "{}");}
    catch {return {};}
  })(),
  set(patch) {
    Object.assign(this.state, patch);
    try {sessionStorage.setItem("folio-flow", JSON.stringify(this.state));} catch {}
    this.listeners.forEach((fn) => fn(this.state));
  },
  get(key) {return this.state[key];},
  listeners: new Set(),
  subscribe(fn) {this.listeners.add(fn);return () => this.listeners.delete(fn);}
};

function useFlow() {
  const [, force] = React.useReducer((x) => x + 1, 0);
  React.useEffect(() => FlowStore.subscribe(force), []);
  return [FlowStore.state, FlowStore.set.bind(FlowStore)];
}

Object.assign(window, {
  ROUTES, useHashRoute, SiteHeader, SiteFooter, FolioMark,
  StepLayout, FlowProgress, FlowStore, useFlow, NavLink
});
