/* global React, Icon, Button, Chip, ScreenHeader, Panel, SectionLabel, AgentNote, Dropzone, EXTRACTED, CANDIDATE */
const { useState: useOnb } = React;

function ScrOnboarding({ onDone }) {
  const [step, setStep] = useOnb("choice"); // choice | upload | extracting | review | form
  const [path, setPath] = useOnb(null);     // "resume" | "fresh"

  return (
    <div style={{ maxWidth: 880, margin: "0 auto", padding: "8px 0 40px" }}>
      <ScreenHeader
        eyebrow="Step 1 · Setup"
        title="Set up your profile"
        lede="The more it has to work from, the better every résumé, intro, and answer gets. Start with a résumé, or build from scratch."
      />

      {step === "choice" && (
        <div className="cad-rise">
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
            <ChoiceCard icon="upload" title="Upload your résumé" sub="Offerroom reads it and pre-fills everything. Fastest start."
              cta="Upload résumé" primary onClick={() => { setPath("resume"); setStep("upload"); }}/>
            <ChoiceCard icon="edit" title="Start from scratch" sub="No résumé handy. Answer a short profile form and Offerroom writes your first one."
              cta="Build a profile" onClick={() => { setPath("fresh"); setStep("form"); }}/>
          </div>

          <div style={{ display: "flex", alignItems: "center", gap: 14, margin: "20px 0" }}>
            <span style={{ flex: 1, height: 1, background: "var(--ink-100)" }}/>
            <span style={{ fontSize: 12, color: "var(--fg-3)" }}>or speed it up</span>
            <span style={{ flex: 1, height: 1, background: "var(--ink-100)" }}/>
          </div>

          <Panel pad={16} style={{ display: "flex", alignItems: "center", gap: 14 }}>
            <span style={{ width: 40, height: 40, borderRadius: 8, background: "var(--slate-tint)", color: "#2A3744", display: "grid", placeItems: "center", flexShrink: 0 }}>
              <Icon name="link" size={18}/>
            </span>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 14, fontWeight: 500 }}>Connect LinkedIn</div>
              <div style={{ fontSize: 12.5, color: "var(--fg-2)" }}>Pre-fill your profile and let Offerroom map your network for warm intros later.</div>
            </div>
            <Button variant="secondary" size="sm" icon="link" onClick={() => { setPath("fresh"); setStep("form"); }}>Connect</Button>
          </Panel>
        </div>
      )}

      {step === "upload" && (
        <div className="cad-rise" style={{ display: "flex", flexDirection: "column", gap: 14 }}>
          <Dropzone icon="fileText" tall title="Drop your latest résumé, or click to browse"
            sub="PDF, DOCX, or a LinkedIn export. This becomes the starting point."
            onClick={() => setStep("extracting")}/>
          <Panel pad={16}>
            <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12 }}>
              <div>
                <div style={{ fontSize: 13.5, fontWeight: 500 }}>Have older versions? Add them too. <span style={{ color: "var(--fg-2)", fontWeight: 400 }}>Optional</span></div>
                <div style={{ fontSize: 12, color: "var(--fg-2)", marginTop: 2 }}>Different résumés show more of your range. Everything lands in your private memory.</div>
              </div>
              <Button variant="ghost" size="sm" icon="plus">Add version</Button>
            </div>
          </Panel>
          <div><Button variant="ghost" size="sm" onClick={() => setStep("choice")}>← Back</Button></div>
        </div>
      )}

      {step === "extracting" && <Extracting onDone={() => setStep("review")}/>}

      {step === "review" && (
        <div className="cad-rise" style={{ display: "flex", flexDirection: "column", gap: 16 }}>
          <AgentNote time="just now"
            actions={<>
              <Button variant="primary" size="sm" icon="check" onClick={() => setStep("form")}>Looks right, continue</Button>
              <Button variant="ghost" size="sm" icon="edit" onClick={() => setStep("form")}>Edit fields</Button>
            </>}>
            Your résumé is read and the basics are pulled out. Two less-certain fields are flagged, give them a glance.
          </AgentNote>
          <Panel pad={0}>
            <div style={{ padding: "12px 18px", borderBottom: "1px solid var(--ink-100)", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
              <SectionLabel>Auto-extracted profile</SectionLabel>
              <span style={{ fontSize: 11.5, color: "var(--fg-2)" }}>from Resume — Okonkwo 2026.pdf</span>
            </div>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr" }}>
              {EXTRACTED.map((f, i) => <ExtractRow key={i} f={f} last={i >= EXTRACTED.length - 2}/>)}
            </div>
          </Panel>
        </div>
      )}

      {step === "form" && <ProfileForm prefilled={path === "resume"} onBack={() => setStep(path === "resume" ? "review" : "choice")} onDone={onDone}/>}
    </div>
  );
}

const ChoiceCard = ({ icon, title, sub, cta, primary, onClick }) => (
  <Panel pad={20} style={{ display: "flex", flexDirection: "column", gap: 0, minHeight: 188 }}>
    <span style={{ width: 44, height: 44, borderRadius: 10, background: primary ? "var(--cardinal-50)" : "var(--paper-sunken)", color: primary ? "var(--cardinal)" : "var(--fg-1)", display: "grid", placeItems: "center" }}>
      <Icon name={icon} size={20}/>
    </span>
    <div style={{ fontFamily: "var(--font-display)", fontSize: 19, fontWeight: 500, marginTop: 16 }}>{title}</div>
    <div style={{ fontSize: 13, color: "var(--fg-2)", marginTop: 6, lineHeight: 1.5, flex: 1 }}>{sub}</div>
    <div style={{ marginTop: 16 }}>
      <Button variant={primary ? "primary" : "secondary"} size="md" icon={icon} onClick={onClick}>{cta}</Button>
    </div>
  </Panel>
);

function Extracting({ onDone }) {
  const [pct, setPct] = useOnb(0);
  React.useEffect(() => {
    const lines = ["Reading document…", "Extracting work history…", "Detecting skills and dates…", "Pre-filling your profile…"];
    let p = 0;
    const t = setInterval(() => { p += 9 + Math.random() * 8; if (p >= 100) { p = 100; clearInterval(t); setTimeout(onDone, 450); } setPct(Math.min(100, Math.round(p))); }, 260);
    return () => clearInterval(t);
  }, []);
  const lines = ["Reading document", "Extracting work history", "Detecting skills and dates", "Pre-filling your profile"];
  const activeLine = Math.min(lines.length - 1, Math.floor(pct / 25));
  return (
    <Panel pad={28} className="cad-rise">
      <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
        <span className="cad-pulse-dot"/>
        <span style={{ fontFamily: "var(--font-display)", fontSize: 19, fontWeight: 500 }}>Offerroom is reading your résumé</span>
      </div>
      <div style={{ height: 6, borderRadius: 999, background: "var(--paper-sunken)", marginTop: 18, overflow: "hidden" }}>
        <div style={{ height: "100%", width: pct + "%", background: "#8C1515", borderRadius: 999, transition: "width 240ms cubic-bezier(0.2,0.7,0.1,1)" }}/>
      </div>
      <div style={{ marginTop: 16, display: "flex", flexDirection: "column", gap: 8 }}>
        {lines.map((l, i) => (
          <div key={i} style={{ display: "flex", alignItems: "center", gap: 9, fontSize: 13, color: i <= activeLine ? "var(--fg-1)" : "var(--fg-3)" }}>
            <span style={{ width: 16, height: 16, borderRadius: 999, display: "grid", placeItems: "center", background: i < activeLine ? "#5A7150" : "transparent", color: "#fff", border: i < activeLine ? "none" : "1.5px solid var(--ink-100)" }}>
              {i < activeLine && <Icon name="check" size={10}/>}
            </span>
            {l}
          </div>
        ))}
      </div>
    </Panel>
  );
}

const ExtractRow = ({ f, last }) => {
  const conf = { high: { tone: "sage", label: "High" }, med: { tone: "slate", label: "Likely" }, low: { tone: "ochre", label: "Check this" } }[f.confidence];
  return (
    <div style={{ padding: "12px 18px", borderBottom: last ? "none" : "1px solid var(--ink-50)", borderRight: "1px solid var(--ink-50)" }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 8 }}>
        <span style={{ fontSize: 11, color: "var(--fg-2)" }}>{f.field}</span>
        {f.confidence !== "high" && <Chip tone={conf.tone === "ochre" ? "draft" : "info"} dot={true}>{conf.label}</Chip>}
      </div>
      <div style={{ fontSize: 14, fontWeight: 500, marginTop: 3, color: "var(--fg-1)" }}>{f.value}</div>
    </div>
  );
};

function ProfileForm({ prefilled, onBack, onDone }) {
  const v = prefilled ? CANDIDATE : {};
  return (
    <div className="cad-rise" style={{ display: "flex", flexDirection: "column", gap: 16 }}>
      <AgentNote time="now">
        {prefilled ? "What could be filled from your résumé is in. Confirm a few details and the build starts." : "No résumé, no problem. Add the essentials and your first one gets written from here."}
      </AgentNote>
      <Panel pad={22}>
        <SectionLabel style={{ marginBottom: 16 }}>Your profile</SectionLabel>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
          <Field label="Full name" value={v.fullName} placeholder="Jane Rivera"/>
          <Field label="Email" value={v.email} placeholder="you@example.com"/>
          <Field label="Current or most recent title" value={prefilled ? "Senior Product Manager, Growth" : ""} placeholder="Product Manager"/>
          <Field label="Location" value={v.location} placeholder="City, Country"/>
          <Field label="Years of experience" value={prefilled ? "6" : ""} placeholder="5"/>
          <Field label="Work authorization" value={v.visa} placeholder="Citizen / visa status" flag={prefilled}/>
        </div>
        <div style={{ height: 1, background: "var(--ink-50)", margin: "20px 0" }}/>
        <SectionLabel style={{ marginBottom: 12 }}>Target</SectionLabel>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
          <Field label="Target roles" value={prefilled ? "Senior PM, Payments / Growth" : ""} placeholder="Roles you want"/>
          <Field label="Geographies" value={prefilled ? "SF Bay Area, Remote US" : ""} placeholder="Where you'll work"/>
        </div>
      </Panel>
      <div style={{ display: "flex", justifyContent: "space-between" }}>
        <Button variant="ghost" size="md" onClick={onBack}>← Back</Button>
        <Button variant="primary" size="md" icon="arrow" onClick={onDone}>Next · build my memory</Button>
      </div>
    </div>
  );
}

const Field = ({ label, value, placeholder, flag }) => (
  <label style={{ display: "block" }}>
    <div style={{ fontSize: 12, color: "var(--fg-2)", marginBottom: 6, display: "flex", alignItems: "center", gap: 6 }}>
      {label}{flag && <Chip tone="draft">Confirm</Chip>}
    </div>
    <input defaultValue={value || ""} placeholder={placeholder} style={{
      width: "100%", boxSizing: "border-box", padding: "10px 12px", borderRadius: 6,
      border: value ? "1px solid rgba(31,27,22,0.14)" : "1px solid var(--ink-100)",
      background: "#fff", fontFamily: "var(--font-sans)", fontSize: 14, color: "var(--fg-1)", outline: "none",
    }}/>
  </label>
);

window.ScrOnboarding = ScrOnboarding;
