/* Onboarding flow — first-run experience */

const Onboarding = ({ onFinish }) => {
  const [step, setStep] = React.useState(0);
  const [country, setCountry] = React.useState("US");
  const [entity, setEntity] = React.useState(null);
  const [accountConnected, setAccountConnected] = React.useState(false);
  const [importProgress, setImportProgress] = React.useState(0);

  const country_ = window.COUNTRIES.find(c => c.code === country);

  React.useEffect(() => {
    if (country_) setEntity(country_.entities[0].id);
  }, [country]);

  // Animate import progress on step 4
  React.useEffect(() => {
    if (step !== 4) return;
    setImportProgress(0);
    const t = setInterval(() => {
      setImportProgress(p => {
        if (p >= 100) { clearInterval(t); return 100; }
        return p + 4;
      });
    }, 80);
    return () => clearInterval(t);
  }, [step]);

  const steps = ["Welcome", "Country", "Entity", "Connect", "Import", "Done"];

  const next = () => setStep(s => Math.min(s + 1, steps.length - 1));
  const back = () => setStep(s => Math.max(s - 1, 0));

  return (
    <div style={{
      position: "fixed", inset: 0, background: "var(--bg)", zIndex: 1000,
      display: "flex", flexDirection: "column",
    }}>
      {/* Header */}
      <div style={{
        padding: "20px 36px",
        display: "flex", alignItems: "center", justifyContent: "space-between",
        borderBottom: "1px solid var(--hairline)",
      }}>
        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
          <div style={{
            width: 36, height: 36, borderRadius: 9,
            background: "var(--ink)",
            overflow: "hidden",
            boxShadow: "0 1px 2px oklch(0.3 0.05 50 / 0.15)",
          }}>
            <img src="assets/creatorboard-icon.png" alt="" style={{ width: "100%", height: "100%", display: "block" }} />
          </div>
          <span style={{ fontFamily: "var(--font-display)", fontSize: 24 }}>CreatorBoard</span>
        </div>

        {/* Step indicator */}
        <div style={{ display: "flex", gap: 6, alignItems: "center" }}>
          {steps.map((s, i) => (
            <div key={s} style={{
              width: i === step ? 28 : 8, height: 8, borderRadius: 4,
              background: i <= step ? "var(--primary)" : "var(--hairline-strong)",
              transition: "width 0.25s, background 0.25s",
            }} />
          ))}
        </div>

        <button className="btn btn-ghost btn-sm" onClick={onFinish}>Skip setup</button>
      </div>

      {/* Body */}
      <div style={{ flex: 1, overflowY: "auto", display: "grid", placeItems: "center", padding: 40 }}>
        <div style={{ width: "100%", maxWidth: 640 }} key={step}>
          {step === 0 && <WelcomeStep onNext={next} />}
          {step === 1 && <CountryStep country={country} setCountry={setCountry} onNext={next} onBack={back} />}
          {step === 2 && <EntityStep country={country_} entity={entity} setEntity={setEntity} onNext={next} onBack={back} />}
          {step === 3 && <ConnectStep connected={accountConnected} setConnected={setAccountConnected} onNext={next} onBack={back} />}
          {step === 4 && <ImportStep progress={importProgress} onNext={next} />}
          {step === 5 && <DoneStep country={country_} entity={entity} accountConnected={accountConnected} onFinish={onFinish} />}
        </div>
      </div>
    </div>
  );
};

const stepCard = {
  textAlign: "center",
  padding: "40px 0",
};

const WelcomeStep = ({ onNext }) => (
  <div className="onb-step" style={stepCard}>
    <div style={{ fontSize: 64, marginBottom: 12 }}>
      <img src="assets/creatorboard-icon.png" alt="" style={{ width: 96, height: 96, borderRadius: 20, boxShadow: "0 6px 24px oklch(0.3 0.05 50 / 0.18)" }} />
    </div>
    <h1 style={{ fontFamily: "var(--font-display)", fontSize: 52, letterSpacing: "-0.015em", lineHeight: 1.05, margin: 0 }}>
      Welcome to CreatorBoard
    </h1>
    <p style={{ fontSize: 17, color: "var(--ink-soft)", maxWidth: 460, margin: "16px auto 32px", lineHeight: 1.5 }}>
      The finance app built for YouTube creators. Connect your accounts, auto-categorize
      every charge, and have your tax ledger ready in real time.
    </p>
    <div style={{ display: "flex", flexDirection: "column", gap: 8, maxWidth: 380, margin: "0 auto 32px", textAlign: "left" }}>
      {[
        { icon: "link", text: "Connect 40+ banks, cards, and platforms" },
        { icon: "sparkles", text: "Auto-categorize income and expenses" },
        { icon: "file", text: "Generate P&L and tax-ready reports" },
      ].map(f => (
        <div key={f.text} style={{ display: "flex", alignItems: "center", gap: 12, padding: "10px 14px", background: "var(--surface)", borderRadius: 12, border: "1px solid var(--hairline)" }}>
          <div style={{
            width: 36, height: 36, borderRadius: 10, background: "var(--primary-soft)",
            color: "var(--primary-ink)", display: "grid", placeItems: "center",
          }}>
            <Icon name={f.icon} size={16} />
          </div>
          <span style={{ fontSize: 14, fontWeight: 500 }}>{f.text}</span>
        </div>
      ))}
    </div>
    <button className="btn btn-primary" style={{ padding: "12px 28px", fontSize: 15 }} onClick={onNext}>
      Get started <Icon name="chevronRight" size={14} />
    </button>
    <div style={{ fontSize: 12, color: "var(--muted)", marginTop: 14 }}>Takes about 60 seconds</div>
  </div>
);

const CountryStep = ({ country, setCountry, onNext, onBack }) => (
  <div>
    <StepHeader
      eyebrow="Step 1 of 5"
      title="Where are you based?"
      sub="Drives your tax rates, due dates, and reporting format"
    />
    <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 8, marginTop: 28 }}>
      {window.COUNTRIES.map(c => (
        <button key={c.code}
          onClick={() => setCountry(c.code)}
          style={{
            padding: 16, borderRadius: 12, cursor: "pointer",
            background: country === c.code ? "var(--primary-soft)" : "var(--surface)",
            border: "1.5px solid " + (country === c.code ? "var(--primary)" : "var(--hairline)"),
            color: country === c.code ? "var(--primary-ink)" : "var(--ink)",
            textAlign: "left",
            display: "flex", alignItems: "center", gap: 12,
          }}>
          <span style={{ fontSize: 26 }}>{c.flag}</span>
          <div>
            <div style={{ fontWeight: 500, fontSize: 14 }}>{c.name}</div>
            <div style={{ fontSize: 11, color: country === c.code ? "var(--primary-ink)" : "var(--muted)", opacity: 0.8 }}>{c.currency}</div>
          </div>
        </button>
      ))}
    </div>
    <StepFooter onBack={onBack} onNext={onNext} nextLabel="Continue" />
  </div>
);

const EntityStep = ({ country, entity, setEntity, onNext, onBack }) => {
  const selected = country.entities.find(e => e.id === entity) || country.entities[0];
  return (
    <div>
      <StepHeader
        eyebrow="Step 2 of 5"
        title={`Your business in ${country.name}`}
        sub="Determines blended tax rate and report format"
      />
      <div style={{ display: "flex", flexDirection: "column", gap: 8, marginTop: 28 }}>
        {country.entities.map(e => (
          <button key={e.id}
            onClick={() => setEntity(e.id)}
            style={{
              padding: 14, borderRadius: 12, cursor: "pointer", textAlign: "left",
              background: entity === e.id ? "var(--primary-soft)" : "var(--surface)",
              border: "1.5px solid " + (entity === e.id ? "var(--primary)" : "var(--hairline)"),
              display: "flex", alignItems: "center", gap: 14,
            }}>
            <div style={{
              width: 26, height: 26, borderRadius: "50%",
              border: "1.5px solid " + (entity === e.id ? "var(--primary)" : "var(--hairline-strong)"),
              background: entity === e.id ? "var(--primary)" : "transparent",
              display: "grid", placeItems: "center", flexShrink: 0,
            }}>
              {entity === e.id && <Icon name="check" size={14} color="white" />}
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ fontWeight: 500, fontSize: 14 }}>{e.name}</div>
              <div style={{ fontSize: 12, color: "var(--muted)", marginTop: 2 }}>{e.rateNote}</div>
            </div>
            <div style={{ fontFamily: "var(--font-display)", fontSize: 22, color: entity === e.id ? "var(--primary-ink)" : "var(--ink-soft)", flexShrink: 0 }}>
              {(e.rate * 100).toFixed(0)}%
            </div>
          </button>
        ))}
      </div>
      <StepFooter onBack={onBack} onNext={onNext} nextLabel="Continue" />
    </div>
  );
};

const ConnectStep = ({ connected, setConnected, onNext, onBack }) => {
  const [openModal, setOpenModal] = React.useState(false);
  return (
    <div>
      <StepHeader
        eyebrow="Step 3 of 5"
        title="Connect your first account"
        sub="Bank, card, or creator platform — we'll auto-import 90 days"
      />
      <div style={{ marginTop: 28 }}>
        {connected ? (
          <div className="card" style={{ padding: 22, display: "flex", alignItems: "center", gap: 14, background: "var(--income-soft)", border: "1.5px solid oklch(0.7 0.1 155)" }}>
            <div style={{
              width: 44, height: 44, borderRadius: 12, background: "oklch(0.55 0.13 155)",
              display: "grid", placeItems: "center", color: "white",
            }}>
              <Icon name="check" size={22} />
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ fontWeight: 500 }}>Mercury Business Checking connected</div>
              <div style={{ fontSize: 12, color: "var(--ink-soft)" }}>·· 4421 · 84 transactions ready to import</div>
            </div>
            <button className="btn btn-sm btn-ghost" onClick={() => setConnected(false)}>Change</button>
          </div>
        ) : (
          <>
            <button onClick={() => setOpenModal(true)}
              style={{
                width: "100%", padding: 24, borderRadius: 14, cursor: "pointer",
                background: "var(--surface)", border: "2px dashed var(--hairline-strong)",
                display: "flex", flexDirection: "column", alignItems: "center", gap: 10,
              }}>
              <div style={{
                width: 48, height: 48, borderRadius: 12, background: "var(--primary-soft)",
                color: "var(--primary-ink)", display: "grid", placeItems: "center",
              }}>
                <Icon name="plus" size={22} />
              </div>
              <div style={{ fontWeight: 500, fontSize: 15 }}>Choose an institution</div>
              <div style={{ fontSize: 12.5, color: "var(--muted)" }}>
                Banks, cards, PayPal, Wise, Revolut, YouTube, Stripe…
              </div>
            </button>
            <div className="card-quiet" style={{ marginTop: 14, padding: 14, fontSize: 12.5, color: "var(--ink-soft)" }}>
              <Icon name="link" size={13} /> &nbsp;Read-only access · bank-grade encryption via Plaid · disconnect anytime
            </div>
          </>
        )}
      </div>
      <StepFooter
        onBack={onBack}
        onNext={onNext}
        nextLabel={connected ? "Import transactions" : "Skip for now"}
      />
      <ConnectAccountModal
        open={openModal}
        onClose={() => setOpenModal(false)}
        onConnect={() => { setConnected(true); setOpenModal(false); }}
      />
    </div>
  );
};

const ImportStep = ({ progress, onNext }) => {
  React.useEffect(() => {
    if (progress >= 100) {
      const t = setTimeout(onNext, 500);
      return () => clearTimeout(t);
    }
  }, [progress, onNext]);

  const milestones = [
    { at: 20, label: "Connecting securely…" },
    { at: 45, label: "Pulling 90 days of transactions" },
    { at: 70, label: "Auto-categorizing with rules" },
    { at: 95, label: "Building your dashboard" },
  ];
  const currentLabel = [...milestones].reverse().find(m => progress >= m.at)?.label || milestones[0].label;

  return (
    <div style={stepCard}>
      <div style={{ fontSize: 12, color: "var(--muted)", textTransform: "uppercase", letterSpacing: "0.06em", marginBottom: 12 }}>
        Step 4 of 5
      </div>
      <h2 style={{ fontFamily: "var(--font-display)", fontSize: 36, margin: 0, letterSpacing: "-0.015em" }}>
        Setting up your books
      </h2>
      <div style={{ fontSize: 16, color: "var(--ink-soft)", marginTop: 8 }}>{currentLabel}</div>

      <div style={{ maxWidth: 320, margin: "30px auto 0", height: 8, background: "var(--surface-2)", borderRadius: 4, overflow: "hidden" }}>
        <div style={{
          height: "100%", background: "linear-gradient(90deg, var(--primary), oklch(0.55 0.16 320))",
          width: progress + "%", transition: "width 0.18s ease",
        }} />
      </div>

      <div style={{ marginTop: 32, display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 8, maxWidth: 480, margin: "32px auto 0" }}>
        {milestones.map(m => (
          <div key={m.at} style={{
            padding: 12, borderRadius: 10, fontSize: 11,
            background: progress >= m.at ? "var(--income-soft)" : "var(--surface-2)",
            color: progress >= m.at ? "var(--income-text-strong)" : "var(--muted)",
            display: "flex", alignItems: "center", gap: 6, justifyContent: "center",
          }}>
            {progress >= m.at ? <Icon name="check" size={12} /> :
              <div style={{ width: 10, height: 10, borderRadius: "50%", border: "2px solid var(--hairline-strong)" }} />}
            <span style={{ fontWeight: 500 }}>{m.label.split(" ").slice(0, 2).join(" ")}</span>
          </div>
        ))}
      </div>
    </div>
  );
};

const DoneStep = ({ country, entity, accountConnected, onFinish }) => {
  const selectedEntity = country.entities.find(e => e.id === entity) || country.entities[0];
  return (
    <div style={stepCard}>
      <div style={{
        width: 84, height: 84, borderRadius: "50%", background: "var(--income-soft)",
        color: "var(--income-text)", display: "grid", placeItems: "center", margin: "0 auto 20px",
      }}>
        <Icon name="check" size={42} />
      </div>
      <h2 style={{ fontFamily: "var(--font-display)", fontSize: 44, margin: 0, letterSpacing: "-0.015em" }}>
        You're all set
      </h2>
      <p style={{ fontSize: 15, color: "var(--ink-soft)", maxWidth: 460, margin: "12px auto 28px" }}>
        Your dashboard is ready. We've already auto-categorized most of your transactions —
        check the Review tab to confirm the rest.
      </p>

      <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 8, maxWidth: 480, margin: "0 auto 28px" }}>
        {[
          { l: "Jurisdiction", v: country.flag + " " + country.code },
          { l: "Entity", v: selectedEntity.name.split(" ")[0] },
          { l: "Tax reserve", v: (selectedEntity.rate * 100).toFixed(0) + "%" },
        ].map(s => (
          <div key={s.l} style={{ padding: 12, background: "var(--surface)", borderRadius: 10, border: "1px solid var(--hairline)" }}>
            <div style={{ fontSize: 10.5, color: "var(--muted)", textTransform: "uppercase", letterSpacing: "0.05em" }}>{s.l}</div>
            <div style={{ fontFamily: "var(--font-display)", fontSize: 18, marginTop: 4 }}>{s.v}</div>
          </div>
        ))}
      </div>

      <button className="btn btn-primary" style={{ padding: "12px 28px", fontSize: 15 }} onClick={() => onFinish({ countryCode: country.code, currency: country.currency, taxEntity: entity })}>
        Go to dashboard <Icon name="chevronRight" size={14} />
      </button>
    </div>
  );
};

const StepHeader = ({ eyebrow, title, sub }) => (
  <div style={{ textAlign: "center" }}>
    <div style={{ fontSize: 12, color: "var(--muted)", textTransform: "uppercase", letterSpacing: "0.06em", marginBottom: 8 }}>
      {eyebrow}
    </div>
    <h2 style={{ fontFamily: "var(--font-display)", fontSize: 36, margin: 0, letterSpacing: "-0.015em" }}>{title}</h2>
    <div style={{ color: "var(--muted)", marginTop: 8, fontSize: 14 }}>{sub}</div>
  </div>
);

const StepFooter = ({ onBack, onNext, nextLabel = "Continue" }) => (
  <div style={{ display: "flex", justifyContent: "space-between", marginTop: 28 }}>
    <button className="btn" onClick={onBack}>
      <Icon name="chevronLeft" size={14} /> Back
    </button>
    <button className="btn btn-primary" onClick={onNext}>
      {nextLabel} <Icon name="chevronRight" size={14} />
    </button>
  </div>
);

window.Onboarding = Onboarding;
