// flow-late.jsx — Steps 09-11: Edit, Auto-update, Dashboard

// ── Step 09: Edit ──────────────────────────────────────────────────────────

function EditScreen() {
  const [flow] = useFlow();
  const [, navigate] = useHashRoute();
  const persona = window.PERSONAS[flow.persona || "maya"];
  const [tone, setTone] = React.useState("default");
  const [hidden, setHidden] = React.useState({});
  const [draft, setDraft] = React.useState(null);
  const [content, setContent] = React.useState(null);
  const [messages, setMessages] = React.useState([
    { who: "folio", text: "Your portfolio is live. What would you like to refine? You can also click anything in the preview to edit it directly." },
  ]);
  const [input, setInput] = React.useState("");
  const suggestions = [
    "Make this more senior",
    "Rewrite for recruiters",
    "Use a warmer tone",
    "Hide my older repos",
    "Make it more founder-focused",
  ];
  const sections = content?.sections || [];
  const heroSection = sections.find(s => s.type === "hero") || sections[0];
  const aboutSection = sections.find(s => s.type === "about") || heroSection;
  const projectsSection = sections.find(s => s.type === "projects");
  const projectRows = (projectsSection?.items?.length
    ? projectsSection.items.map((item, index) => ({
        name: item.title || item.name || `Project ${index + 1}`,
        tag: item.metadata?.language || item.tag || item.kind || "source",
        stat: item.metadata?.stars ? `${item.metadata.stars} stars` : item.stat || "",
        desc: item.summary || item.description || item.desc || "",
      }))
    : persona.projects).slice(0, 4);

  React.useEffect(() => {
    let cancelled = false;
    if (!window.FolioBackend?.getLatestDraft) return;
    window.FolioBackend.getLatestDraft()
      .then(loaded => {
        if (cancelled || !loaded) return;
        setDraft(loaded);
        setContent(loaded.content);
      })
      .catch(() => {});
    return () => { cancelled = true; };
  }, []);

  const persistContent = (nextContent) => {
    setContent(nextContent);
    if (!draft?.id || !window.FolioBackend?.saveDraftContent) return;
    window.FolioBackend.saveDraftContent(draft.id, nextContent)
      .then(updated => {
        setDraft(updated);
        setContent(updated.content);
      })
      .catch(error => {
        setMessages(m => [...m, { who: "folio", text: error.message || "Direct edit could not be saved." }]);
      });
  };

  const updateTopLevel = (key, value) => {
    if (!content) return;
    persistContent({ ...content, [key]: value });
  };

  const updateSection = (sectionId, patch) => {
    if (!content || !sectionId) return;
    persistContent({
      ...content,
      sections: content.sections.map(section => section.id === sectionId ? { ...section, ...patch } : section)
    });
  };

  const send = (text) => {
    if (!text.trim()) return;
    setMessages(m => [...m, { who: "user", text }]);
    setInput("");
    if (draft?.id && window.FolioBackend?.chatEditDraft) {
      window.FolioBackend.chatEditDraft(draft.id, text)
        .then(result => {
          if (result?.draft) {
            setDraft(result.draft);
            setContent(result.draft.content);
          }
          setMessages(m => [...m, { who: "folio", text: result?.reply || "Draft updated and saved." }]);
        })
        .catch(error => {
          setMessages(m => [...m, { who: "folio", text: error.message || "AI edit failed." }]);
        });
      return;
    }
    setTimeout(() => {
      const replies = {
        "senior": "Tightened your headline and bio — fewer adjectives, more specifics. Headline now reads as Principal-level.",
        "recruiter": "Reordered for recruiter scanning: years of experience first, languages prominent, projects with metrics on top.",
        "warm": "Softened the bio — replaced 'I build' with 'I help teams build' and added a closing line about who you like working with.",
        "hide": "Hid 14 older repos from public view (last commit > 18 months). They're still searchable on GitHub.",
        "founder": "Reframed bio around what you ship and what you've shipped before. Added Substack subs as a credibility signal.",
      };
      const key = Object.keys(replies).find(k => text.toLowerCase().includes(k)) || "senior";
      setMessages(m => [...m, { who: "folio", text: replies[key] }]);
    }, 700);
  };

  return (
    <div>
      <SiteHeader minimal current="/edit"/>
      <FlowProgress current="09"/>
      <div className="original-editor-grid" style={{ display: "grid", gridTemplateColumns: "1fr 380px", height: "calc(100vh - 64px - 49px)", borderTop: "0.5px solid var(--rule)" }}>
        {/* Live preview */}
        <div className="original-editor-preview" style={{ background: "var(--paper-2)", overflow: "auto", padding: 24, position: "relative" }}>
          <div style={{ position: "sticky", top: 0, background: "color-mix(in oklch, var(--paper-2) 90%, transparent)", backdropFilter: "blur(8px)", padding: "10px 14px", borderRadius: "var(--radius)", border: "0.5px solid var(--rule)", display: "flex", alignItems: "center", gap: 12, marginBottom: 20, zIndex: 5 }}>
            <div style={{ display: "flex", gap: 5 }}>
              <div style={{ width: 9, height: 9, borderRadius: 5, background: "#e8e6e0" }}/>
              <div style={{ width: 9, height: 9, borderRadius: 5, background: "#e8e6e0" }}/>
              <div style={{ width: 9, height: 9, borderRadius: 5, background: "#e8e6e0" }}/>
            </div>
            <div style={{ fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--ink-3)", flex: 1 }}>
              <span className="chip live" style={{ marginRight: 8 }}>LIVE</span>
              {flow.domain?.value || "mayaokonkwo.com"}
            </div>
            <div className="eyebrow" style={{ fontSize: 10 }}>EDIT MODE · CLICK TO REFINE</div>
          </div>

          {/* Editable mini portfolio */}
          <div className="original-preview-shell" style={{ background: "#fdfbf6", padding: "60px 80px", borderRadius: "var(--radius-lg)", border: "0.5px solid var(--rule)", maxWidth: 980, margin: "0 auto", boxShadow: "0 30px 60px -30px rgba(0,0,0,0.18)" }}>
            <div className="eyebrow" style={{ color: "#a09889", marginBottom: 20 }}>{(content?.templateLabel || persona.role).toUpperCase()} · SOURCE-CITED</div>
            <Editable as="h1" onCommit={value => updateSection(heroSection?.id, { title: value })} style={{ fontFamily: "Newsreader, serif", fontSize: 80, lineHeight: 0.95, letterSpacing: "-0.025em", color: "#1a1814", marginBottom: 24 }}>
              {heroSection?.title || persona.name}.
            </Editable>
            <Editable as="div" onCommit={value => updateTopLevel("headline", value)} style={{ fontFamily: "Newsreader, serif", fontStyle: "italic", fontSize: 26, color: "#3a3530", marginBottom: 16 }}>
              {content?.headline || persona.headline}
            </Editable>
            <Editable as="p" onCommit={value => updateSection(aboutSection?.id, { body: value })} style={{ fontSize: 16, color: "#5a5249", lineHeight: 1.55, maxWidth: 640, marginBottom: 36 }}>
              {aboutSection?.body || persona.bio}
            </Editable>

            <div className="eyebrow" style={{ color: "#a09889", marginBottom: 16 }}>SELECTED WORK</div>
            <div style={{ display: "flex", flexDirection: "column", gap: 0 }}>
              {projectRows.map((p, i) => (
                <ProjectRow key={i} p={p} hidden={hidden[i]} onToggle={() => setHidden({ ...hidden, [i]: !hidden[i] })}/>
              ))}
            </div>
          </div>
        </div>

        {/* Right: chat panel */}
        <div className="original-editor-panel" style={{ borderLeft: "0.5px solid var(--rule)", display: "flex", flexDirection: "column", background: "var(--paper)" }}>
          <div style={{ padding: "16px 20px", borderBottom: "0.5px solid var(--rule)" }}>
            <div className="eyebrow" style={{ marginBottom: 4, color: "var(--accent)" }}>STEP 09 · LIGHT EDITING</div>
            <div style={{ fontFamily: "var(--font-serif)", fontSize: 22, letterSpacing: "-0.015em" }}>Refine, don't rebuild.</div>
          </div>
          <div style={{ flex: 1, overflow: "auto", padding: 20, display: "flex", flexDirection: "column", gap: 12 }}>
            {messages.map((m, i) => (
              <div key={i} style={{
                alignSelf: m.who === "user" ? "flex-end" : "flex-start",
                maxWidth: "86%",
                padding: "10px 14px",
                background: m.who === "user" ? "var(--ink)" : "var(--paper-2)",
                color: m.who === "user" ? "var(--paper)" : "var(--ink)",
                border: m.who === "user" ? 0 : "0.5px solid var(--rule)",
                borderRadius: "var(--radius)",
                fontSize: 14,
                lineHeight: 1.5,
                fontFamily: m.who === "folio" ? "var(--font-serif)" : "var(--font-sans)",
              }}>
                {m.text}
              </div>
            ))}
          </div>
          <div style={{ padding: 14, borderTop: "0.5px solid var(--rule)" }}>
            <div style={{ display: "flex", gap: 6, flexWrap: "wrap", marginBottom: 10 }}>
              {suggestions.slice(0, 3).map(s => (
                <button key={s} onClick={() => send(s)} style={{ padding: "5px 10px", background: "var(--paper-2)", border: "0.5px solid var(--rule)", borderRadius: 999, fontSize: 11, fontFamily: "var(--font-mono)", color: "var(--ink-2)", cursor: "pointer" }}>
                  {s}
                </button>
              ))}
            </div>
            <div style={{ display: "flex", gap: 8, alignItems: "center", border: "0.5px solid var(--rule-2)", borderRadius: "var(--radius)", padding: "8px 8px 8px 14px" }}>
              <input
                value={input}
                onChange={e => setInput(e.target.value)}
                onKeyDown={e => e.key === "Enter" && send(input)}
                placeholder="Make this more…"
                style={{ flex: 1, border: 0, background: "transparent", outline: "none", fontSize: 14, color: "var(--ink)" }}
              />
              <button onClick={() => send(input)} className="btn btn-primary" style={{ padding: "8px 12px", fontSize: 12 }}>
                <Icon name="send" size={12}/>
              </button>
            </div>
            <button onClick={() => navigate("/auto")} className="btn btn-ghost" style={{ width: "100%", justifyContent: "center", marginTop: 12, fontSize: 13 }}>
              Done editing — set up auto-update <span className="arr">→</span>
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

function Editable({ as: Tag = "div", children, style, onCommit }) {
  const [hover, setHover] = React.useState(false);
  const ref = React.useRef(null);
  React.useEffect(() => {
    if (ref.current && ref.current.textContent !== String(children ?? "")) {
      ref.current.textContent = String(children ?? "");
    }
  }, [children]);
  return (
    <Tag
      ref={ref}
      contentEditable
      suppressContentEditableWarning
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      onBlur={e => onCommit && onCommit(e.currentTarget.textContent || "")}
      style={{
        ...style,
        outline: hover ? "1px dashed oklch(0.62 0.14 40)" : "1px dashed transparent",
        outlineOffset: 4,
        cursor: "text",
        transition: "outline-color 140ms",
      }}
    >
      {children}
    </Tag>
  );
}

function ProjectRow({ p, hidden, onToggle }) {
  const [hov, setHov] = React.useState(false);
  return (
    <div onMouseEnter={() => setHov(true)} onMouseLeave={() => setHov(false)} style={{
      display: "grid",
      gridTemplateColumns: "120px 1fr auto auto",
      gap: 24,
      padding: "20px 0",
      borderTop: "0.5px solid #e9e6df",
      alignItems: "center",
      opacity: hidden ? 0.35 : 1,
      transition: "opacity 160ms",
      position: "relative",
    }}>
      <div style={{ fontFamily: "JetBrains Mono, monospace", fontSize: 10, letterSpacing: "0.08em", textTransform: "uppercase", color: "#a09889" }}>{p.tag}</div>
      <div>
        <div style={{ fontFamily: "Newsreader, serif", fontSize: 22, color: "#1a1814", lineHeight: 1.1 }}>{p.name}</div>
        <div style={{ fontSize: 13, color: "#5a5249", marginTop: 4 }}>{p.desc}</div>
      </div>
      <div style={{ fontFamily: "JetBrains Mono, monospace", fontSize: 11, color: "#888" }}>{p.stat}</div>
      <button
        onClick={onToggle}
        style={{
          width: 28, height: 28, borderRadius: 14,
          border: "0.5px solid #e0ddd4",
          background: hov ? "#fdfbf6" : "transparent",
          opacity: hov || hidden ? 1 : 0.3,
          transition: "all 140ms",
          cursor: "pointer",
          color: "#5a5249",
          display: "flex", alignItems: "center", justifyContent: "center",
        }}
      >
        <Icon name={hidden ? "eye-off" : "eye"} size={12}/>
      </button>
    </div>
  );
}

// ── Step 10: Auto-update ───────────────────────────────────────────────────

function AutoScreen() {
  const [flow, setFlow] = useFlow();
  const [, navigate] = useHashRoute();
  const [freq, setFreq] = React.useState(flow.autoFreq || "weekly");
  const [triggers, setTriggers] = React.useState(flow.autoTriggers || { github: true, resume: true, writing: false });

  const freqs = [
    { id: "manual", label: "Manual only", sub: "I'll update when I want to" },
    { id: "weekly", label: "Weekly", sub: "Every Sunday night, quiet refresh" },
    { id: "monthly", label: "Monthly", sub: "First of the month" },
  ];

  return (
    <div>
      <SiteHeader minimal current="/auto"/>
      <StepLayout
        stepNum="10"
        eyebrow="STAY UP TO DATE WITHOUT THINKING ABOUT IT"
        title={<>How should it <em style={{ fontStyle: "italic", color: "var(--accent)" }}>refresh</em>?</>}
        sub="Folio can keep your portfolio in sync with your work. Pick the cadence and the triggers — change them later from the dashboard."
      >
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 64 }}>
          <div>
            <div className="eyebrow" style={{ marginBottom: 16 }}>FREQUENCY</div>
            <div style={{ display: "flex", flexDirection: "column", gap: 10, marginBottom: 40 }}>
              {freqs.map(f => {
                const isSel = freq === f.id;
                return (
                  <button key={f.id} onClick={() => { setFreq(f.id); setFlow({ autoFreq: f.id }); }} style={{
                    display: "flex", alignItems: "center", gap: 16, padding: "18px 20px",
                    background: isSel ? "var(--paper-2)" : "var(--paper)",
                    border: isSel ? "1px solid var(--ink)" : "0.5px solid var(--rule)",
                    borderRadius: "var(--radius)", textAlign: "left", cursor: "pointer", color: "var(--ink)",
                  }}>
                    <div style={{ width: 16, height: 16, borderRadius: 8, border: "0.5px solid", borderColor: isSel ? "var(--ink)" : "var(--rule-2)", background: isSel ? "var(--ink)" : "transparent", display: "flex", alignItems: "center", justifyContent: "center" }}>
                      {isSel && <div style={{ width: 6, height: 6, borderRadius: 3, background: "var(--paper)" }}/>}
                    </div>
                    <div style={{ flex: 1 }}>
                      <div style={{ fontWeight: 500 }}>{f.label}</div>
                      <div style={{ fontSize: 13, color: "var(--ink-3)" }}>{f.sub}</div>
                    </div>
                  </button>
                );
              })}
            </div>
          </div>

          <div>
            <div className="eyebrow" style={{ marginBottom: 16 }}>TRIGGERS</div>
            <div style={{ display: "flex", flexDirection: "column", gap: 10, marginBottom: 40 }}>
              <TriggerRow label="When GitHub changes" sub="New repos, pinned changes, README updates" on={triggers.github} onToggle={() => setTriggers({...triggers, github: !triggers.github})}/>
              <TriggerRow label="When resume is updated" sub="We watch the file you uploaded" on={triggers.resume} onToggle={() => setTriggers({...triggers, resume: !triggers.resume})}/>
              <TriggerRow label="When new writing is published" sub="Substack, Medium, Dev.to feeds" on={triggers.writing} onToggle={() => setTriggers({...triggers, writing: !triggers.writing})}/>
            </div>
          </div>
        </div>

        {/* Suggestion preview */}
        <div style={{ marginTop: 24, padding: "20px 24px", background: "var(--paper-2)", border: "0.5px dashed var(--rule-2)", borderRadius: "var(--radius)", display: "flex", alignItems: "center", gap: 18 }}>
          <div style={{ width: 36, height: 36, borderRadius: 18, background: "var(--accent-soft)", color: "var(--accent)", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
            <Icon name="spark" size={16}/>
          </div>
          <div style={{ flex: 1 }}>
            <div style={{ fontFamily: "var(--font-serif)", fontSize: 17, fontStyle: "italic", color: "var(--ink)" }}>
              Sample alert you'll get
            </div>
            <div style={{ fontSize: 13, color: "var(--ink-3)", marginTop: 2 }}>
              "New GitHub project detected: <span style={{ fontFamily: "var(--font-mono)" }}>tinyeval</span> · 820 stars in two weeks. Add it to your portfolio?"
            </div>
          </div>
          <button className="btn btn-ghost" style={{ padding: "8px 14px", fontSize: 12 }}>Looks good</button>
        </div>

        <FlowFooter back="/edit" onContinue={() => navigate("/dashboard")} continueLabel="Open dashboard" rightHint="Last step →"/>
      </StepLayout>
    </div>
  );
}

function TriggerRow({ label, sub, on, onToggle }) {
  return (
    <div style={{ display: "flex", alignItems: "center", padding: "16px 20px", background: "var(--paper)", border: "0.5px solid var(--rule)", borderRadius: "var(--radius)" }}>
      <div style={{ flex: 1 }}>
        <div style={{ fontWeight: 500 }}>{label}</div>
        <div style={{ fontSize: 13, color: "var(--ink-3)" }}>{sub}</div>
      </div>
      <button onClick={onToggle} style={{
        width: 38, height: 22, borderRadius: 999,
        background: on ? "var(--accent)" : "var(--rule-2)",
        border: 0, cursor: "pointer", padding: 0, position: "relative",
        transition: "background 160ms",
      }}>
        <div style={{
          position: "absolute", top: 2, left: on ? 18 : 2,
          width: 18, height: 18, borderRadius: 9,
          background: "var(--paper)",
          boxShadow: "0 1px 3px rgba(0,0,0,0.2)",
          transition: "left 160ms cubic-bezier(.2,.8,.2,1)",
        }}/>
      </button>
    </div>
  );
}

// ── Step 11: Dashboard ─────────────────────────────────────────────────────

function DashboardScreen() {
  const [flow] = useFlow();
  const persona = window.PERSONAS[flow.persona || "maya"];
  const [, navigate] = useHashRoute();

  return (
    <div>
      <SiteHeader minimal current="/dashboard"/>
      <div style={{ borderBottom: "0.5px solid var(--rule)", padding: "var(--space-6) 0" }}>
        <div className="container" style={{ display: "flex", alignItems: "flex-end", justifyContent: "space-between" }}>
          <div>
            <div className="eyebrow" style={{ color: "var(--accent)", marginBottom: 8 }}>DASHBOARD</div>
            <h1 style={{ fontSize: 48, lineHeight: 1, letterSpacing: "-0.02em" }}>Welcome back, {persona.name.split(" ")[0]}.</h1>
            <p style={{ marginTop: 12, color: "var(--ink-3)", fontFamily: "var(--font-serif)", fontStyle: "italic", fontSize: 17 }}>
              Your portfolio updated 6 minutes ago. Three things want your attention.
            </p>
          </div>
          <div style={{ display: "flex", alignItems: "center", gap: 14, padding: "10px 16px", background: "var(--paper)", border: "0.5px solid var(--rule)", borderRadius: 999 }}>
            <span className="chip live" style={{ border: 0, background: "transparent", paddingLeft: 0 }}>LIVE</span>
            <span style={{ fontFamily: "var(--font-mono)", fontSize: 13 }}>{flow.domain?.value || "mayaokonkwo.com"}</span>
            <Icon name="external" size={14} style={{ color: "var(--ink-3)" }}/>
          </div>
        </div>
      </div>

      <div className="container" style={{ padding: "var(--space-7) var(--space-6)" }}>
        {/* Stats strip */}
        <div style={{ display: "grid", gridTemplateColumns: "repeat(5, 1fr)", gap: 0, border: "0.5px solid var(--rule)", borderRadius: "var(--radius-lg)", overflow: "hidden", background: "var(--paper)", marginBottom: 32 }}>
          <Stat label="HEALTH SCORE" value="86" sub="Strong" trend="+4 this week"/>
          <Stat label="VIEWS · 7D" value="1,284" sub="↑ 38% WoW" trend="240 unique"/>
          <Stat label="LEADS" value="6" sub="3 unread" trend="From 4 sources"/>
          <Stat label="UPDATED" value="6m" sub="ago" trend="Auto · weekly"/>
          <Stat label="UPTIME" value="100%" sub="last 30d" trend="0 incidents" last/>
        </div>

        <div style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr", gap: 24 }}>
          {/* Left col */}
          <div style={{ display: "flex", flexDirection: "column", gap: 24 }}>
            {/* Suggested improvements */}
            <Section title="Suggested by Folio" eyebrow="WHAT TO LOOK AT">
              <div style={{ display: "flex", flexDirection: "column", gap: 0 }}>
                <Suggestion type="trend" title="Your tinyeval repo is trending — feature it?" detail="820 stars in 14 days · currently hidden in 'older work'" cta="Promote to top"/>
                <Suggestion type="signal" title="Recruiters clicked your AI project 12 times" detail="vllm-gateway · most clicks from Anthropic, Replicate, Modal" cta="Add metric"/>
                <Suggestion type="warn" title="Your headline could be stronger for ML roles" detail="'Full-stack' is broad — try 'Inference Infrastructure Engineer'" cta="Try suggestion"/>
                <Suggestion type="info" title="New domain suggestion: maya.engineer is available" detail="$48/yr · matches your recommended positioning" cta="Reserve it" last/>
              </div>
            </Section>

            {/* Visitors graph */}
            <Section title="Visitors" eyebrow="LAST 30 DAYS">
              <VisitorsChart/>
              <div style={{ marginTop: 24, display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 24, paddingTop: 20, borderTop: "0.5px solid var(--rule)" }}>
                <MiniMetric label="TOP REFERRER" value="news.ycombinator.com" sub="412 visits"/>
                <MiniMetric label="TOP PROJECT" value="vllm-gateway" sub="612 reads"/>
                <MiniMetric label="AVG. TIME" value="2:14" sub="↑ 0:18 WoW"/>
                <MiniMetric label="BOUNCE" value="34%" sub="↓ 6 pts"/>
              </div>
            </Section>

            {/* Connected sources */}
            <Section title="Connected sources" eyebrow="SYNC STATUS">
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
                <SourceStatus id="github" status="ok" detail="Last synced 6 minutes ago · 47 repos"/>
                <SourceStatus id="linkedin" status="ok" detail="Last synced 2 days ago · 4 positions"/>
                <SourceStatus id="resume" status="warn" detail="Hasn't been re-uploaded since launch"/>
                <SourceStatus id="substack" status="ok" detail="Last post pulled 11 hours ago"/>
              </div>
            </Section>
          </div>

          {/* Right col */}
          <div style={{ display: "flex", flexDirection: "column", gap: 24 }}>
            {/* Quick actions */}
            <Section title="Quick actions" eyebrow="DO SOMETHING">
              <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
                <Action onClick={() => navigate("/edit")} icon="edit" label="Edit portfolio" sub="Refine with chat or click-to-edit"/>
                <Action onClick={() => navigate("/auto")} icon="refresh" label="Auto-update settings" sub="Currently: weekly · GitHub triggered"/>
                <Action onClick={() => navigate("/design")} icon="frame" label="Try a new design" sub="Editorial · switch any time"/>
                <Action onClick={() => {}} icon="bell" label="Notification preferences" sub="Email · digest"/>
              </div>
            </Section>

            {/* Recent activity */}
            <Section title="Activity" eyebrow="RECENT EVENTS">
              <Activity time="6m" text="Auto-update synced from GitHub" detail="vllm-gateway README updated"/>
              <Activity time="2h" text="Lead captured" detail="Hiring manager from Modal — ML platform role"/>
              <Activity time="1d" text="Loadbearing post published" detail="'Why your eval set keeps drifting' — added to writing section"/>
              <Activity time="3d" text="Health score increased" detail="82 → 86 · stronger headline match"/>
              <Activity time="6d" text="Domain renewed" detail="mayaokonkwo.com · next renewal May 2027" last/>
            </Section>

            {/* Plan */}
            <div style={{ background: "var(--ink)", color: "var(--paper)", borderRadius: "var(--radius-lg)", padding: 24 }}>
              <div style={{ fontFamily: "var(--font-mono)", fontSize: 10, letterSpacing: "0.12em", color: "rgba(253,251,246,0.6)", marginBottom: 6 }}>YOUR PLAN</div>
              <div style={{ fontFamily: "var(--font-serif)", fontSize: 28, marginBottom: 4 }}>Pro · $99/yr</div>
              <div style={{ fontSize: 13, color: "rgba(253,251,246,0.7)", marginBottom: 20 }}>Renews May 1, 2027 · 364 days from now</div>
              <button className="btn" style={{ background: "var(--paper)", color: "var(--ink)", padding: "10px 16px", fontSize: 13 }}>Manage billing</button>
            </div>
          </div>
        </div>
      </div>

      <SiteFooter/>
    </div>
  );
}

function Stat({ label, value, sub, trend, last }) {
  return (
    <div style={{ padding: 24, borderRight: last ? 0 : "0.5px solid var(--rule)" }}>
      <div className="eyebrow" style={{ marginBottom: 10 }}>{label}</div>
      <div style={{ display: "flex", alignItems: "baseline", gap: 8 }}>
        <span style={{ fontFamily: "var(--font-serif)", fontSize: 40, lineHeight: 1, letterSpacing: "-0.02em" }}>{value}</span>
        <span style={{ fontSize: 12, color: "var(--ink-3)" }}>{sub}</span>
      </div>
      <div style={{ fontFamily: "var(--font-mono)", fontSize: 10, letterSpacing: "0.06em", color: "var(--ink-4)", marginTop: 8 }}>{trend}</div>
    </div>
  );
}

function Section({ title, eyebrow, children }) {
  return (
    <section style={{ background: "var(--paper)", border: "0.5px solid var(--rule)", borderRadius: "var(--radius-lg)", padding: 24 }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 18 }}>
        <div style={{ fontFamily: "var(--font-serif)", fontSize: 22, letterSpacing: "-0.015em" }}>{title}</div>
        {eyebrow && <div className="eyebrow" style={{ fontSize: 10 }}>{eyebrow}</div>}
      </div>
      {children}
    </section>
  );
}

function Suggestion({ type, title, detail, cta, last }) {
  const colors = {
    trend: { bg: "oklch(0.94 0.06 145)", fg: "oklch(0.45 0.14 145)", icon: "trend" },
    signal: { bg: "var(--accent-soft)", fg: "var(--accent-deep)", icon: "spark" },
    warn: { bg: "oklch(0.95 0.08 75)", fg: "oklch(0.55 0.14 60)", icon: "spark" },
    info: { bg: "oklch(0.93 0.04 230)", fg: "oklch(0.45 0.12 230)", icon: "globe" },
  };
  const c = colors[type];
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 16, padding: "14px 0", borderBottom: last ? 0 : "0.5px solid var(--rule)" }}>
      <div style={{ width: 32, height: 32, borderRadius: 16, background: c.bg, color: c.fg, display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
        <Icon name={c.icon} size={14}/>
      </div>
      <div style={{ flex: 1 }}>
        <div style={{ fontWeight: 500, fontSize: 14 }}>{title}</div>
        <div style={{ fontSize: 12, color: "var(--ink-3)" }}>{detail}</div>
      </div>
      <button className="btn btn-ghost" style={{ padding: "6px 12px", fontSize: 12 }}>{cta}</button>
    </div>
  );
}

function VisitorsChart() {
  const data = [12, 18, 14, 24, 22, 28, 36, 32, 30, 38, 42, 36, 48, 54, 52, 60, 64, 58, 66, 72, 68, 76, 84, 78, 88, 92, 86, 96, 102, 110];
  const max = Math.max(...data);
  return (
    <div style={{ display: "flex", alignItems: "flex-end", gap: 4, height: 140 }}>
      {data.map((v, i) => (
        <div key={i} style={{
          flex: 1,
          height: `${(v / max) * 100}%`,
          background: i === data.length - 1 ? "var(--accent)" : "var(--ink-3)",
          opacity: 0.3 + (i / data.length) * 0.7,
          borderRadius: "2px 2px 0 0",
        }}/>
      ))}
    </div>
  );
}

function MiniMetric({ label, value, sub }) {
  return (
    <div>
      <div className="eyebrow" style={{ fontSize: 9, marginBottom: 6 }}>{label}</div>
      <div style={{ fontFamily: "var(--font-mono)", fontSize: 14, color: "var(--ink)" }}>{value}</div>
      <div style={{ fontSize: 11, color: "var(--ink-3)", marginTop: 2 }}>{sub}</div>
    </div>
  );
}

function SourceStatus({ id, status, detail }) {
  const s = window.SOURCES.find(x => x.id === id);
  const dotColor = status === "ok" ? "oklch(0.65 0.16 145)" : status === "warn" ? "oklch(0.7 0.16 75)" : "var(--accent)";
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 12, padding: 12, background: "var(--paper-2)", border: "0.5px solid var(--rule)", borderRadius: "var(--radius)" }}>
      <SourceGlyph id={id} small/>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
          <div style={{ width: 7, height: 7, borderRadius: 4, background: dotColor }}/>
          <div style={{ fontWeight: 500, fontSize: 13 }}>{s?.label || id}</div>
        </div>
        <div style={{ fontSize: 11, color: "var(--ink-3)", marginTop: 2 }}>{detail}</div>
      </div>
    </div>
  );
}

function Action({ onClick, icon, label, sub }) {
  return (
    <button onClick={onClick} style={{ display: "flex", alignItems: "center", gap: 14, padding: "14px 16px", background: "var(--paper-2)", border: "0.5px solid var(--rule)", borderRadius: "var(--radius)", textAlign: "left", cursor: "pointer", color: "var(--ink)", transition: "border-color 140ms" }}
      onMouseEnter={e => e.currentTarget.style.borderColor = "var(--ink)"}
      onMouseLeave={e => e.currentTarget.style.borderColor = "var(--rule)"}
    >
      <Icon name={icon} size={16} style={{ color: "var(--ink-2)" }}/>
      <div style={{ flex: 1 }}>
        <div style={{ fontWeight: 500, fontSize: 14 }}>{label}</div>
        <div style={{ fontSize: 12, color: "var(--ink-3)" }}>{sub}</div>
      </div>
      <Icon name="arrow-right" size={14} style={{ color: "var(--ink-3)" }}/>
    </button>
  );
}

function Activity({ time, text, detail, last }) {
  return (
    <div style={{ display: "flex", gap: 14, padding: "12px 0", borderBottom: last ? 0 : "0.5px solid var(--rule)" }}>
      <div style={{ fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--ink-4)", letterSpacing: "0.04em", width: 40, paddingTop: 3, flexShrink: 0 }}>{time}</div>
      <div style={{ flex: 1 }}>
        <div style={{ fontSize: 13, color: "var(--ink)" }}>{text}</div>
        <div style={{ fontSize: 12, color: "var(--ink-3)", fontStyle: "italic", fontFamily: "var(--font-serif)" }}>{detail}</div>
      </div>
    </div>
  );
}

Object.assign(window, { EditScreen, AutoScreen, DashboardScreen });
