// flow-early.jsx — Steps 01-04: Goal, Connect, Scan, Direction

function cleanConnectedSources(value) {
  if (!value || typeof value !== "object") return {};
  const serialized = JSON.stringify(value);
  if (/okonkwo|mayaokonkwo/i.test(serialized)) return {};

  return Object.entries(value).reduce((next, [id, item]) => {
    if (!item || typeof item !== "object" || !item.value) return next;
    next[id] = { value: item.value };
    return next;
  }, {});
}

// ── Step 01: Goal ──────────────────────────────────────────────────────────

function GoalScreen() {
  const [flow, setFlow] = useFlow();
  const [, navigate] = useHashRoute();
  const [selected, setSelected] = React.useState(flow.goal || null);

  const onSelect = (g) => {
    setSelected(g);
    setFlow({ goal: g });
  };
  const onContinue = () => {
    if (selected) navigate("/connect");
  };

  return (
    <div>
      <SiteHeader minimal current="/goal"/>
      <StepLayout
        stepNum="01"
        eyebrow="WHAT'S THIS FOR"
        title={<>What do you want this portfolio to <em style={{ fontStyle: "italic", color: "var(--accent)" }}>help you do?</em></>}
        sub="Pick the closest one. We'll tune everything — voice, what we feature, what we hide — to match. You can change it later."
      >
        <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 16, marginBottom: 56 }}>
          {window.GOALS.map((g, i) => (
            <button
              key={g.id}
              onClick={() => onSelect(g.id)}
              className="entrance"
              style={{
                animationDelay: `${i * 60}ms`,
                textAlign: "left",
                padding: "28px 24px",
                background: "var(--paper)",
                border: selected === g.id ? "1px solid var(--ink)" : "0.5px solid var(--rule)",
                borderRadius: "var(--radius-lg)",
                cursor: "pointer",
                transition: "all 180ms ease",
                position: "relative",
                color: "var(--ink)",
              }}
              onMouseEnter={e => { if (selected !== g.id) e.currentTarget.style.borderColor = "var(--rule-2)"; }}
              onMouseLeave={e => { if (selected !== g.id) e.currentTarget.style.borderColor = "var(--rule)"; }}
            >
              <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 28 }}>
                <Icon name={g.icon} size={26} stroke={1.25} style={{ color: selected === g.id ? "var(--accent)" : "var(--ink-2)" }}/>
                <div style={{
                  width: 18, height: 18, borderRadius: 9,
                  border: "0.5px solid",
                  borderColor: selected === g.id ? "var(--ink)" : "var(--rule-2)",
                  background: selected === g.id ? "var(--ink)" : "transparent",
                  color: "var(--paper)",
                  display: "flex", alignItems: "center", justifyContent: "center",
                  transition: "all 160ms",
                }}>
                  {selected === g.id && <Icon name="check" size={11} stroke={2}/>}
                </div>
              </div>
              <div style={{ fontFamily: "var(--font-serif)", fontSize: 28, lineHeight: 1.05, marginBottom: 6, letterSpacing: "-0.015em" }}>{g.label}</div>
              <div style={{ color: "var(--ink-3)", fontSize: 14 }}>{g.sub}</div>
            </button>
          ))}
        </div>

        <FlowFooter
          back={null}
          rightHint={selected ? `${window.GOALS.find(g => g.id === selected).label} — continue` : "Pick one to continue"}
          onContinue={selected ? onContinue : null}
        />
      </StepLayout>
    </div>
  );
}

// ── Step 02: Connect Sources ───────────────────────────────────────────────

function ConnectScreen() {
  const [flow, setFlow] = useFlow();
  const [, navigate] = useHashRoute();
  const [connected, setConnected] = React.useState(() => cleanConnectedSources(flow.connected));
  const [openInput, setOpenInput] = React.useState(null);
  const connectedKey = JSON.stringify(flow.connected || {});

  React.useEffect(() => {
    setConnected(cleanConnectedSources(flow.connected));
  }, [connectedKey]);

  React.useEffect(() => {
    const onConnected = (event) => setConnected(cleanConnectedSources(event.detail));
    window.addEventListener("folio:connected", onConnected);
    return () => window.removeEventListener("folio:connected", onConnected);
  }, []);

  const toggle = (id) => {
    setOpenInput(openInput === id ? null : id);
  };
  const setValue = (id, val) => {
    const next = { ...connected, [id]: val ? { value: val } : undefined };
    Object.keys(next).forEach(k => next[k] === undefined && delete next[k]);
    setConnected(next);
    setFlow({ connected: next });
  };

  const count = Object.keys(connected).length;
  const canContinue = count > 0;

  return (
    <div>
      <SiteHeader minimal current="/connect"/>
      <StepLayout
        stepNum="02"
        eyebrow="CONNECT THE WORK YOU'VE ALREADY DONE"
        title={<>Bring what <em style={{ fontStyle: "italic", color: "var(--accent)" }}>already exists.</em></>}
        sub="Add the work Folio is allowed to read: GitHub, resume, LinkedIn PDF export, portfolio links, and a picture. Nothing is posted anywhere."
      >
        <div style={{ display: "grid", gridTemplateColumns: "1fr 320px", gap: 48 }}>
          <div>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
              {window.SOURCES.map(s => {
                const isConnected = !!connected[s.id];
                const isOpen = openInput === s.id;
                return (
                  <div key={s.id}>
                    <button
                      onClick={() => toggle(s.id)}
                      style={{
                        width: "100%",
                        textAlign: "left",
                        padding: "18px 20px",
                        background: isConnected ? "var(--paper-2)" : "var(--paper)",
                        border: isConnected ? "0.5px solid var(--accent)" : "0.5px solid var(--rule)",
                        borderRadius: isOpen ? "10px 10px 0 0" : "var(--radius)",
                        cursor: "pointer",
                        display: "flex",
                        alignItems: "center",
                        gap: 14,
                        transition: "all 160ms ease",
                        color: "var(--ink)",
                      }}
                    >
                      <SourceGlyph id={s.id}/>
                      <div style={{ flex: 1, minWidth: 0 }}>
                        <div style={{ fontWeight: 500, marginBottom: 2 }}>{s.label}</div>
                        <div style={{ fontSize: 12, color: "var(--ink-3)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
                          {isConnected ? connected[s.id].value : s.desc}
                        </div>
                      </div>
                      {isConnected ? (
                        <span className="chip" style={{ background: "var(--accent)", color: "var(--paper)", border: 0 }}>
                          <Icon name="check" size={10} stroke={2}/> CONNECTED
                        </span>
                      ) : (
                        <Icon name={isOpen ? "x" : "plus"} size={14} style={{ color: "var(--ink-3)" }}/>
                      )}
                    </button>
                    {isOpen && (
                      <div style={{
                        padding: 14,
                        background: "var(--paper-2)",
                        border: "0.5px solid var(--rule)",
                        borderTop: 0,
                        borderRadius: "0 0 10px 10px",
                        display: "flex", gap: 8,
                      }}>
                        <input
                          autoFocus
                          className="input"
                          style={{ padding: "10px 12px", fontSize: 13 }}
                          placeholder={s.id === "links" ? "https://your-link.com" : s.id === "resume" || s.id === "linkedin_pdf" ? "Upload a PDF or document…" : `${s.label} URL or username`}
                          defaultValue={connected[s.id]?.value || ""}
                          onKeyDown={e => {
                            if (e.key === "Enter") { setValue(s.id, e.target.value); setOpenInput(null); }
                            if (e.key === "Escape") setOpenInput(null);
                          }}
                        />
                        <button
                          className="btn btn-primary"
                          style={{ padding: "10px 16px", fontSize: 13 }}
                          onClick={e => { const v = e.currentTarget.parentElement.querySelector("input").value; setValue(s.id, v); setOpenInput(null); }}
                        >
                          Add
                        </button>
                      </div>
                    )}
                  </div>
                );
              })}
            </div>
          </div>

          {/* Right rail — connected summary */}
          <div>
            <div style={{ position: "sticky", top: 96 }}>
              <div className="eyebrow" style={{ marginBottom: 16 }}>CONNECTED · {count}</div>
              <div style={{ border: "0.5px solid var(--rule)", borderRadius: "var(--radius-lg)", padding: "var(--space-5)", background: "var(--paper)" }}>
                {count === 0 ? (
                  <p style={{ fontFamily: "var(--font-serif)", fontStyle: "italic", color: "var(--ink-3)", margin: 0, fontSize: 15, lineHeight: 1.5 }}>
                  Add at least one source. Start with a resume, GitHub, LinkedIn PDF, a link, or your picture.
                  </p>
                ) : (
                  <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
                    {Object.entries(connected).map(([id, v]) => {
                      const s = window.SOURCES.find(x => x.id === id);
                      return (
                        <div key={id} style={{ display: "flex", alignItems: "center", gap: 12, paddingBottom: 12, borderBottom: "0.5px solid var(--rule)" }}>
                          <SourceGlyph id={id} small/>
                          <div style={{ flex: 1, minWidth: 0 }}>
                            <div style={{ fontWeight: 500, fontSize: 13 }}>{s.label}</div>
                            <div style={{ fontSize: 11, fontFamily: "var(--font-mono)", color: "var(--ink-3)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{v.value}</div>
                          </div>
                          <button onClick={() => setValue(id, null)} style={{ background: "transparent", border: 0, color: "var(--ink-4)", cursor: "pointer", padding: 4 }}>
                            <Icon name="x" size={14}/>
                          </button>
                        </div>
                      );
                    })}
                  </div>
                )}
                <button
                  className="btn btn-primary"
                  disabled={!canContinue}
                  onClick={() => navigate("/scan")}
                  style={{
                    width: "100%",
                    justifyContent: "center",
                    marginTop: 20,
                    opacity: canContinue ? 1 : 0.4,
                    cursor: canContinue ? "pointer" : "not-allowed",
                  }}
                >
                  Scan my work <span className="arr">→</span>
                </button>
                <div style={{ fontFamily: "var(--font-mono)", fontSize: 10, letterSpacing: "0.08em", color: "var(--ink-4)", textAlign: "center", marginTop: 12 }}>
                  TAKES ABOUT 60 SECONDS
                </div>
              </div>
              <div style={{ marginTop: 24, fontFamily: "var(--font-serif)", fontStyle: "italic", color: "var(--ink-3)", fontSize: 14, lineHeight: 1.5 }}>
                Or, build from a name and role only — manual mode.
              </div>
            </div>
          </div>
        </div>
      </StepLayout>
    </div>
  );
}

function SourceGlyph({ id, small = false }) {
  const sz = small ? 24 : 32;
  const map = {
    github: <Icon name="github" size={small ? 14 : 18}/>,
    linkedin_pdf: <Icon name="linkedin" size={small ? 14 : 18}/>,
    resume: <Icon name="file-text" size={small ? 14 : 18}/>,
    links: <Icon name="external" size={small ? 14 : 18}/>,
    image: <Icon name="user" size={small ? 14 : 18}/>,
  };
  const initial = (window.SOURCES.find(s => s.id === id)?.label || "?")[0];
  return (
    <div style={{
      width: sz, height: sz, borderRadius: 6,
      background: "var(--paper-3)",
      border: "0.5px solid var(--rule)",
      display: "flex", alignItems: "center", justifyContent: "center",
      flexShrink: 0,
      color: "var(--ink-2)",
      fontFamily: "var(--font-mono)", fontSize: 11,
    }}>
      {map[id] || initial}
    </div>
  );
}

// ── Step 03: AI Scan ───────────────────────────────────────────────────────

function ScanScreen() {
  const [flow] = useFlow();
  const [, navigate] = useHashRoute();
  const [progress, setProgress] = React.useState(0);
  const [logIdx, setLogIdx] = React.useState(0);

  const persona = window.PERSONAS[flow.persona || "maya"];
  const sourceCount = Object.keys(cleanConnectedSources(flow.connected)).length;

  const log = [
    "Loading approved source items from your Folio workspace…",
    "Parsing resume, GitHub, LinkedIn URL, and image signals where connected…",
    "Extracting project names, roles, skills, dates, and links…",
    "Checking each generated claim against saved source citations…",
    "Detecting positioning from the strongest approved evidence…",
    "Selecting projects and proof points by relevance…",
    "Preparing template-specific portfolio sections…",
    "Flagging anything that needs your review…",
    "Saving the generation state to your draft workspace…",
    "Done. Found your strongest work.",
  ];

  React.useEffect(() => {
    let p = 0;
    const id = setInterval(() => {
      p += 1.6;
      if (p >= 100) {
        setProgress(100);
        clearInterval(id);
        setTimeout(() => navigate("/direction"), 900);
        return;
      }
      setProgress(p);
      setLogIdx(Math.min(log.length - 1, Math.floor((p / 100) * log.length)));
    }, 80);
    return () => clearInterval(id);
  }, []);

  return (
    <div>
      <SiteHeader minimal current="/scan"/>
      <FlowProgress current="03"/>
      <div style={{
        minHeight: "calc(100vh - 64px - 49px)",
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        padding: "var(--space-7) var(--space-6)",
      }}>
        <div style={{ maxWidth: 760, width: "100%", textAlign: "center" }}>
          <div className="eyebrow" style={{ color: "var(--accent)", marginBottom: 28 }}>STEP 03 — READING YOUR WORK</div>

          <div style={{ position: "relative", display: "inline-block", marginBottom: 40 }}>
            <ScanRingLoader/>
          </div>

          <h1 style={{ fontSize: "clamp(40px, 5.4vw, 80px)", lineHeight: 1, letterSpacing: "-0.025em", marginBottom: 20 }}>
            Finding your <em style={{ fontStyle: "italic", color: "var(--accent)" }}>strongest work.</em>
          </h1>
          <p style={{ fontFamily: "var(--font-serif)", fontStyle: "italic", fontSize: 22, color: "var(--ink-2)", lineHeight: 1.5, marginBottom: 56 }}>
            Reading {sourceCount} {sourceCount === 1 ? "source" : "sources"}. Don't refresh — we're nearly there.
          </p>

          {/* Progress bar */}
          <div style={{
            width: "100%",
            height: 2,
            background: "var(--rule)",
            position: "relative",
            marginBottom: 14,
            overflow: "hidden",
          }}>
            <div style={{
              position: "absolute",
              left: 0, top: 0,
              height: "100%",
              width: `${progress}%`,
              background: "var(--accent)",
              transition: "width 80ms linear",
            }}/>
          </div>
          <div style={{ display: "flex", justifyContent: "space-between", fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--ink-3)", letterSpacing: "0.06em", marginBottom: 56 }}>
            <span>{Math.floor(progress)}%</span>
            <span>00:{String(Math.max(0, Math.floor(60 - progress * 0.6))).padStart(2, "0")} REMAINING</span>
          </div>

          {/* Live log */}
          <div style={{
            background: "var(--paper-2)",
            border: "0.5px solid var(--rule)",
            borderRadius: "var(--radius)",
            padding: "20px 24px",
            textAlign: "left",
            fontFamily: "var(--font-mono)",
            fontSize: 12,
            lineHeight: 1.8,
            color: "var(--ink-3)",
            maxHeight: 200,
            overflow: "hidden",
          }}>
            {log.slice(0, logIdx + 1).map((l, i) => (
              <div key={i} style={{
                color: i === logIdx ? "var(--ink)" : "var(--ink-3)",
                opacity: i === logIdx ? 1 : 0.5 + (i / log.length) * 0.4,
                display: "flex", gap: 10, alignItems: "center",
              }}>
                <span style={{ color: i === logIdx ? "var(--accent)" : "var(--ink-4)" }}>{i === logIdx ? "▸" : "✓"}</span>
                <span>{l}</span>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

function ScanRingLoader() {
  return (
    <div style={{ width: 120, height: 120, position: "relative" }}>
      <div className="spin" style={{
        position: "absolute", inset: 0,
        borderRadius: "50%",
        border: "1px solid transparent",
        borderTopColor: "var(--accent)",
        borderRightColor: "var(--accent)",
      }}/>
      <div style={{
        position: "absolute", inset: 12,
        borderRadius: "50%",
        border: "0.5px solid var(--rule-2)",
      }}/>
      <div style={{
        position: "absolute", inset: 28,
        borderRadius: "50%",
        background: "var(--paper)",
        border: "0.5px solid var(--rule-2)",
        display: "flex", alignItems: "center", justifyContent: "center",
        fontFamily: "var(--font-serif)",
        fontSize: 24,
        fontStyle: "italic",
        color: "var(--accent)",
      }}>F</div>
    </div>
  );
}

// ── Step 04: Direction (3 positioning options) ────────────────────────────

function DirectionScreen() {
  const [flow, setFlow] = useFlow();
  const [, navigate] = useHashRoute();
  const persona = window.PERSONAS[flow.persona || "maya"];
  const [selected, setSelected] = React.useState(flow.direction || persona.positioning.find(p => p.recommended).id);

  const onPick = (id) => { setSelected(id); setFlow({ direction: id }); };

  return (
    <div>
      <SiteHeader minimal current="/direction"/>
      <StepLayout
        stepNum="04"
        eyebrow="THREE WAYS TO POSITION YOU"
        title={<>Three drafts. <em style={{ fontStyle: "italic", color: "var(--accent)" }}>Pick the one</em> that sounds like you.</>}
        sub={`Based on what we read, here are three angles that fit. Your work appears differently in each. You can edit anything later.`}
      >
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 16, marginBottom: 56 }}>
          {persona.positioning.map((p, i) => {
            const isSel = selected === p.id;
            return (
              <button
                key={p.id}
                onClick={() => onPick(p.id)}
                className="entrance"
                style={{
                  animationDelay: `${i * 80}ms`,
                  textAlign: "left",
                  padding: "32px 28px",
                  background: isSel ? "var(--ink)" : "var(--paper)",
                  color: isSel ? "var(--paper)" : "var(--ink)",
                  border: isSel ? "1px solid var(--ink)" : "0.5px solid var(--rule)",
                  borderRadius: "var(--radius-lg)",
                  cursor: "pointer",
                  transition: "all 220ms cubic-bezier(.2,.8,.2,1)",
                  position: "relative",
                  display: "flex", flexDirection: "column", gap: 16,
                  minHeight: 480,
                }}
              >
                <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start" }}>
                  <div className="eyebrow" style={{ color: isSel ? "var(--accent-soft)" : "var(--accent)" }}>
                    OPTION {String.fromCharCode(65 + i)}
                  </div>
                  {p.recommended && (
                    <div className="chip" style={{
                      background: "var(--accent)",
                      color: "var(--paper)",
                      border: 0,
                      fontFamily: "var(--font-mono)",
                      fontSize: 9,
                    }}>
                      ★ RECOMMENDED
                    </div>
                  )}
                </div>

                <div>
                  <div style={{ fontFamily: "var(--font-serif)", fontSize: 30, lineHeight: 1.1, letterSpacing: "-0.015em", marginBottom: 6 }}>{p.headline}</div>
                  <div style={{ fontFamily: "var(--font-serif)", fontStyle: "italic", fontSize: 16, color: isSel ? "rgba(253,251,246,0.7)" : "var(--ink-3)" }}>{p.sub}</div>
                </div>

                <p style={{ fontSize: 14, lineHeight: 1.55, color: isSel ? "rgba(253,251,246,0.86)" : "var(--ink-2)", margin: 0 }}>{p.bio}</p>

                <div style={{ marginTop: "auto", paddingTop: 16, borderTop: `0.5px solid ${isSel ? "rgba(253,251,246,0.18)" : "var(--rule)"}`, display: "flex", flexDirection: "column", gap: 10 }}>
                  <Field isSel={isSel} label="AUDIENCE" value={p.audience}/>
                  <Field isSel={isSel} label="TONE" value={p.tone}/>
                  <Field isSel={isSel} label="FEATURING" value={p.projects.join(" · ")}/>
                </div>

                <div style={{
                  marginTop: 4,
                  alignSelf: "flex-start",
                  padding: "8px 14px",
                  borderRadius: 999,
                  border: `0.5px solid ${isSel ? "var(--paper)" : "var(--rule-2)"}`,
                  fontFamily: "var(--font-mono)",
                  fontSize: 11,
                  letterSpacing: "0.06em",
                  textTransform: "uppercase",
                  display: "flex", alignItems: "center", gap: 8,
                }}>
                  {isSel ? <><Icon name="check" size={11} stroke={2}/> SELECTED</> : "PICK THIS"}
                </div>
              </button>
            );
          })}
        </div>

        <FlowFooter
          back="/connect"
          onContinue={() => navigate("/design")}
          rightHint="Pick a design →"
        />
      </StepLayout>
    </div>
  );
}

function Field({ isSel, label, value }) {
  return (
    <div>
      <div style={{ fontFamily: "var(--font-mono)", fontSize: 9, letterSpacing: "0.12em", color: isSel ? "rgba(253,251,246,0.5)" : "var(--ink-4)", marginBottom: 3 }}>{label}</div>
      <div style={{ fontSize: 13, color: isSel ? "rgba(253,251,246,0.92)" : "var(--ink-2)" }}>{value}</div>
    </div>
  );
}

// ── Shared flow footer ─────────────────────────────────────────────────────

function FlowFooter({ back, onContinue, rightHint, continueLabel = "Continue" }) {
  const [, navigate] = useHashRoute();
  return (
    <div style={{
      display: "flex",
      justifyContent: "space-between",
      alignItems: "center",
      paddingTop: 32,
      borderTop: "0.5px solid var(--rule)",
    }}>
      {back ? (
        <button
          onClick={() => navigate(back)}
          className="btn btn-ghost"
          style={{ padding: "12px 18px", fontSize: 13 }}
        >
          <Icon name="arrow-left" size={14}/> Back
        </button>
      ) : <div/>}
      <div style={{ display: "flex", alignItems: "center", gap: 16 }}>
        {rightHint && (
          <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, letterSpacing: "0.08em", color: "var(--ink-3)", textTransform: "uppercase" }}>
            {rightHint}
          </div>
        )}
        {onContinue && (
          <button
            onClick={onContinue}
            className="btn btn-primary"
          >
            {continueLabel} <span className="arr">→</span>
          </button>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { GoalScreen, ConnectScreen, ScanScreen, DirectionScreen, FlowFooter });
