/* global React, Icon, Wordmark, Mark, UI, DATA */
const { useState: useAuthState, useRef: useAuthRef, useEffect: useAuthEffect } = React;

function AuthFlow({ initialStage = "signin", onEnter }) {
  const [stage, setStage] = useAuthState(initialStage); // signin | otp | onboarding | done
  const [email, setEmail] = useAuthState("");

  if (stage === "signin") return <SignIn email={email} setEmail={setEmail} onContinue={() => setStage("otp")} onSkip={() => onEnter()} />;
  if (stage === "otp") return <OtpVerify email={email} onBack={() => setStage("signin")} onVerified={() => setStage("onboarding")} />;
  if (stage === "onboarding") return <Onboarding email={email} onDone={() => onEnter()} />;
  return null;
}

// ---------- Sign in ----------
function SignIn({ email, setEmail, onContinue, onSkip }) {
  const valid = /\S+@\S+\.\S+/.test(email);
  return (
    <div style={{ display: "flex", height: "100vh", width: "100vw", overflow: "hidden" }}>
      {/* left: form */}
      <div style={{ flex: "0 0 46%", minWidth: 420, display: "flex", flexDirection: "column", padding: "40px 56px", overflowY: "auto" }}>
        <Wordmark size={20} markSize={30} />
        <div style={{ flex: 1, display: "flex", flexDirection: "column", justifyContent: "center", maxWidth: 380, margin: "0 auto", width: "100%" }}>
          <h1 style={{ fontSize: 38, lineHeight: 1.04 }}>Welcome to Docomate</h1>
          <p className="muted" style={{ fontSize: 16, marginTop: 14, lineHeight: 1.5 }}>Automate document workflows with AI agents.</p>

          <div style={{ marginTop: 32 }}>
            <UI.Field label="Work email">
              <input className="input" type="email" placeholder="you@company.com" value={email} onChange={(e) => setEmail(e.target.value)}
                onKeyDown={(e) => e.key === "Enter" && valid && onContinue()} autoFocus style={{ height: 46 }} />
            </UI.Field>
            <UI.Button variant="primary" size="lg" disabled={!valid} onClick={onContinue} style={{ width: "100%", marginTop: 2 }} iconRight="arrow-right">Continue with email</UI.Button>
          </div>

          <div style={{ display: "flex", alignItems: "center", gap: 14, margin: "26px 0" }}>
            <div className="divider" style={{ flex: 1 }} />
            <span className="muted" style={{ fontSize: 12.5, fontWeight: 600 }}>or</span>
            <div className="divider" style={{ flex: 1 }} />
          </div>

          <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
            <button className="btn btn-secondary btn-lg" style={{ width: "100%", borderColor: "var(--ef-border-strong)" }} onClick={onContinue}>
              <GoogleG /> Continue with Google
            </button>
            <button className="btn btn-secondary btn-lg" style={{ width: "100%", borderColor: "var(--ef-border-strong)" }} onClick={onContinue}>
              <MsLogo /> Continue with Microsoft
            </button>
          </div>

          <p className="muted" style={{ fontSize: 12.5, marginTop: 28, lineHeight: 1.6 }}>
            By continuing you agree to Docomate's <span className="link">Terms</span>, <span className="link">Privacy</span>, and <span className="link">Security</span> policies.
          </p>
        </div>
        <div className="muted" style={{ fontSize: 12.5, textAlign: "center" }}>
          New to Docomate? Continue with your email to set up a workspace.
        </div>
      </div>

      {/* right: inverse spotlight */}
      <div style={{ flex: 1, background: "var(--ef-ink-950)", color: "var(--ef-bone)", padding: "56px 64px", display: "flex", flexDirection: "column", justifyContent: "center", position: "relative", overflow: "hidden" }}>
        <div className="eyebrow" style={{ color: "var(--ef-beam-500)" }}>Document intelligence operating system</div>
        <h2 style={{ color: "var(--ef-bone)", fontSize: 46, marginTop: 18, lineHeight: 1.02, maxWidth: 560 }}>
          When a document arrives, read it, transform it, and send it where it belongs.
        </h2>
        <p style={{ color: "var(--ef-ink-300)", fontSize: 16, marginTop: 20, maxWidth: 480, lineHeight: 1.6 }}>
          Build a workflow once. Docomate's agents extract, convert, translate, and deliver every document that follows — without writing code.
        </p>

        <div style={{ marginTop: 40, display: "flex", flexWrap: "wrap", gap: 10, maxWidth: 540 }}>
          {[
            ["inbox", "Input", "var(--ef-cobalt)"], ["sparkles", "Extract", "var(--ef-violet)"],
            ["file-spreadsheet", "Generate CSV", "var(--ef-violet)"], ["send", "Deliver", "var(--ef-success)"],
          ].map(([ic, lb, c], i) => (
            <React.Fragment key={i}>
              <div style={{ display: "flex", alignItems: "center", gap: 9, padding: "9px 14px", background: "var(--ef-ink-900)", border: "1px solid var(--ef-ink-800)", borderRadius: 999 }}>
                <Icon name={ic} size={16} color={c} /><span style={{ fontSize: 13, fontWeight: 700, color: "var(--ef-bone)" }}>{lb}</span>
              </div>
              {i < 3 && <Icon name="arrow-right" size={16} color="var(--ef-ink-500)" style={{ alignSelf: "center" }} />}
            </React.Fragment>
          ))}
        </div>

        <div style={{ marginTop: 48, display: "flex", gap: 40 }}>
          {[["8,420", "documents processed this month"], ["1.4 days", "average review time"], ["12", "marketplace workflows"]].map(([n, l]) => (
            <div key={l}>
              <div style={{ fontSize: 28, fontWeight: 800, letterSpacing: "-0.03em", color: "var(--ef-bone)" }}>{n}</div>
              <div style={{ fontSize: 12.5, color: "var(--ef-ink-400)", marginTop: 3, maxWidth: 130 }}>{l}</div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

// ---------- OTP ----------
function OtpVerify({ email, onBack, onVerified }) {
  const [digits, setDigits] = useAuthState(["", "", "", "", "", ""]);
  const refs = useAuthRef([]);
  const [resent, setResent] = useAuthState(false);
  useAuthEffect(() => { refs.current[0]?.focus(); }, []);
  const setD = (i, v) => {
    if (!/^\d?$/.test(v)) return;
    const next = [...digits]; next[i] = v; setDigits(next);
    if (v && i < 5) refs.current[i + 1]?.focus();
  };
  const onKey = (i, e) => { if (e.key === "Backspace" && !digits[i] && i > 0) refs.current[i - 1]?.focus(); };
  const onPaste = (e) => {
    const t = (e.clipboardData.getData("text") || "").replace(/\D/g, "").slice(0, 6).split("");
    if (t.length) { setDigits([...t, ...Array(6 - t.length).fill("")]); refs.current[Math.min(t.length, 5)]?.focus(); e.preventDefault(); }
  };
  const complete = digits.every((d) => d !== "");
  return (
    <div style={{ display: "flex", height: "100vh", width: "100vw", alignItems: "center", justifyContent: "center", background: "var(--ef-bg)" }}>
      <div style={{ width: 420, padding: "40px 44px", textAlign: "center" }} className="fade-in">
        <div style={{ display: "flex", justifyContent: "center", marginBottom: 8 }}><Mark size={40} radius={11} /></div>
        <h2 style={{ fontSize: 30, marginTop: 18 }}>Check your email</h2>
        <p className="muted" style={{ fontSize: 14.5, marginTop: 12, lineHeight: 1.5 }}>
          We sent a 6-digit code to <span style={{ color: "var(--ef-fg-1)", fontWeight: 700 }}>{email || "you@company.com"}</span>. It expires in 10 minutes.
        </p>

        <div style={{ display: "flex", gap: 10, justifyContent: "center", margin: "30px 0 8px" }} onPaste={onPaste}>
          {digits.map((d, i) => (
            <input key={i} ref={(el) => (refs.current[i] = el)} value={d} maxLength={1} inputMode="numeric"
              onChange={(e) => setD(i, e.target.value)} onKeyDown={(e) => onKey(i, e)}
              className="mono" style={{
                width: 50, height: 60, textAlign: "center", fontSize: 26, fontWeight: 700,
                border: "1px solid var(--ef-border-strong)", borderRadius: 10, background: "var(--ef-bg-raised)", color: "var(--ef-fg-1)",
                outline: "none",
              }} />
          ))}
        </div>

        <UI.Button variant="primary" size="lg" disabled={!complete} onClick={onVerified} style={{ width: "100%", marginTop: 22 }}>Verify and continue</UI.Button>

        <div style={{ marginTop: 20, fontSize: 13.5 }}>
          <span className="muted">Didn't get it? </span>
          {resent ? <span style={{ color: "var(--ef-success)", fontWeight: 700 }}>Code resent</span>
            : <span className="link" onClick={() => setResent(true)}>Resend code</span>}
        </div>
        <div style={{ marginTop: 22 }}>
          <span className="link muted" style={{ fontSize: 13, display: "inline-flex", alignItems: "center", gap: 6 }} onClick={onBack}><Icon name="arrow-left" size={14} /> Use a different email</span>
        </div>
        <p className="muted" style={{ fontSize: 12, marginTop: 28, lineHeight: 1.5 }}>For the demo, enter any 6 digits.</p>
      </div>
    </div>
  );
}

// ---------- Onboarding ----------
function Onboarding({ email, onDone }) {
  const o = DATA.onboarding;
  const [step, setStep] = useAuthState(0);
  const [data, setData] = useAuthState({
    name: "", industry: "Garments / Apparel", role: "Business operator", size: "201–1000",
    workflow: "Purchase order processing", sources: ["Manual upload", "Gmail"], outputs: ["Google Drive", "Email"], invites: [{ email: "", role: "Operator" }],
  });
  const set = (k, v) => setData((d) => ({ ...d, [k]: v }));
  const toggle = (k, v) => setData((d) => ({ ...d, [k]: d[k].includes(v) ? d[k].filter((x) => x !== v) : [...d[k], v] }));

  const steps = ["Workspace", "Industry & role", "First workflow", "Sources & outputs", "Invite team"];
  const canNext = [data.name.trim().length > 1, !!data.industry, !!data.workflow, data.sources.length > 0 && data.outputs.length > 0, true][step];
  const last = step === steps.length - 1;

  const Chips = ({ options, value, multi, k }) => (
    <div style={{ display: "flex", flexWrap: "wrap", gap: 9 }}>
      {options.map((opt) => {
        const sel = multi ? value.includes(opt) : value === opt;
        return <button key={opt} className={`chip ${sel ? "selected" : ""}`} onClick={() => multi ? toggle(k, opt) : set(k, opt)}>
          {sel && <Icon name="check" size={13} color="var(--ef-bone)" />}{opt}</button>;
      })}
    </div>
  );

  return (
    <div style={{ display: "flex", flexDirection: "column", height: "100vh", width: "100vw", background: "var(--ef-bg)" }}>
      <div style={{ padding: "20px 40px", borderBottom: "1px solid var(--ef-border)", display: "flex", alignItems: "center", justifyContent: "space-between" }}>
        <Wordmark size={18} markSize={26} />
        <span className="muted" style={{ fontSize: 13 }}>{email || "you@company.com"}</span>
      </div>

      <div style={{ flex: 1, overflowY: "auto" }}>
        <div style={{ maxWidth: 680, margin: "0 auto", padding: "36px 24px 80px" }}>
          <div style={{ marginBottom: 36 }}><UI.Stepper steps={steps} current={step} /></div>

          <div className="fade-in" key={step}>
            {step === 0 && (
              <div>
                <h2 style={{ fontSize: 32 }}>Set up your workspace</h2>
                <p className="muted" style={{ fontSize: 15, marginTop: 10, marginBottom: 28 }}>A workspace holds your projects, workflows, connectors, and team. You can create more later.</p>
                <UI.Field label="Organization or workspace name" required help="This appears across the product and on your documents.">
                  <input className="input" placeholder="e.g. Fakir Fashion" value={data.name} onChange={(e) => set("name", e.target.value)} autoFocus style={{ height: 46 }} />
                </UI.Field>
                <UI.Field label="Company size">
                  <Chips options={o.companySizes} value={data.size} k="size" />
                </UI.Field>
              </div>
            )}
            {step === 1 && (
              <div>
                <h2 style={{ fontSize: 32 }}>Tell us about your work</h2>
                <p className="muted" style={{ fontSize: 15, marginTop: 10, marginBottom: 28 }}>We'll tailor suggested workflows and connectors to your needs.</p>
                <UI.Field label="What industry are you in?" required><Chips options={o.industries} value={data.industry} k="industry" /></UI.Field>
                <UI.Field label="What's your role?"><Chips options={o.roles} value={data.role} k="role" /></UI.Field>
              </div>
            )}
            {step === 2 && (
              <div>
                <h2 style={{ fontSize: 32 }}>What do you want to automate first?</h2>
                <p className="muted" style={{ fontSize: 15, marginTop: 10, marginBottom: 28 }}>Pick a starting point. We'll suggest a matching marketplace workflow on your dashboard.</p>
                <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
                  {o.firstWorkflow.map((w) => {
                    const sel = data.workflow === w;
                    return (
                      <button key={w} onClick={() => set("workflow", w)} className="card" style={{ textAlign: "left", padding: "16px 18px", cursor: "pointer", borderColor: sel ? "var(--ef-ink-950)" : "var(--ef-border)", background: sel ? "var(--ef-bone-2)" : "var(--ef-bg-raised)", display: "flex", alignItems: "center", gap: 12 }}>
                        <div style={{ width: 22, height: 22, borderRadius: 999, border: sel ? "0" : "1.5px solid var(--ef-border-strong)", background: sel ? "var(--ef-ink-950)" : "transparent", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
                          {sel && <Icon name="check" size={13} color="var(--ef-bone)" />}</div>
                        <span style={{ fontSize: 14, fontWeight: 700, color: "var(--ef-fg-1)" }}>{w}</span>
                      </button>
                    );
                  })}
                </div>
              </div>
            )}
            {step === 3 && (
              <div>
                <h2 style={{ fontSize: 32 }}>Where do documents flow?</h2>
                <p className="muted" style={{ fontSize: 15, marginTop: 10, marginBottom: 28 }}>Choose where documents arrive and where outputs should go. Connect accounts later.</p>
                <UI.Field label="Where will your documents come from?" required><Chips options={o.sources} value={data.sources} multi k="sources" /></UI.Field>
                <UI.Field label="Where should outputs go?" required><Chips options={o.outputs} value={data.outputs} multi k="outputs" /></UI.Field>
              </div>
            )}
            {step === 4 && (
              <div>
                <h2 style={{ fontSize: 32 }}>Invite your team</h2>
                <p className="muted" style={{ fontSize: 15, marginTop: 10, marginBottom: 28 }}>Bring in teammates to build and monitor workflows. You can skip this and invite anyone later.</p>
                {data.invites.map((inv, i) => (
                  <div key={i} style={{ display: "flex", gap: 10, marginBottom: 10 }}>
                    <input className="input" placeholder="teammate@company.com" value={inv.email} style={{ flex: 1, height: 44 }}
                      onChange={(e) => setData((d) => { const inv2 = [...d.invites]; inv2[i] = { ...inv2[i], email: e.target.value }; return { ...d, invites: inv2 }; })} />
                    <select className="select" value={inv.role} style={{ width: 170, height: 44 }}
                      onChange={(e) => setData((d) => { const inv2 = [...d.invites]; inv2[i] = { ...inv2[i], role: e.target.value }; return { ...d, invites: inv2 }; })}>
                      {["Workspace Admin", "Workflow Builder", "Operator", "Reviewer", "Viewer", "Billing Admin"].map((r) => <option key={r}>{r}</option>)}
                    </select>
                    {data.invites.length > 1 && <button className="btn btn-ghost btn-icon" onClick={() => setData((d) => ({ ...d, invites: d.invites.filter((_, j) => j !== i) }))}><Icon name="x" size={16} /></button>}
                  </div>
                ))}
                <button className="link" style={{ fontSize: 13.5, fontWeight: 700, display: "inline-flex", alignItems: "center", gap: 6, marginTop: 4 }}
                  onClick={() => setData((d) => ({ ...d, invites: [...d.invites, { email: "", role: "Operator" }] }))}><Icon name="plus" size={15} /> Add another</button>
              </div>
            )}
          </div>
        </div>
      </div>

      <div style={{ borderTop: "1px solid var(--ef-border)", padding: "16px 40px", display: "flex", justifyContent: "space-between", alignItems: "center", background: "var(--ef-bg)" }}>
        <button className="link muted" style={{ fontSize: 13.5, fontWeight: 600, visibility: step === 0 ? "hidden" : "visible", display: "inline-flex", alignItems: "center", gap: 6 }} onClick={() => setStep((s) => s - 1)}><Icon name="arrow-left" size={15} /> Back</button>
        <div style={{ display: "flex", gap: 12, alignItems: "center" }}>
          {last && <button className="link muted" style={{ fontSize: 13.5, fontWeight: 600 }} onClick={onDone}>Skip for now</button>}
          <UI.Button variant={last ? "accent" : "primary"} disabled={!canNext} iconRight={last ? "arrow-right" : "arrow-right"}
            onClick={() => last ? onDone() : setStep((s) => s + 1)}>{last ? "Create workspace" : "Continue"}</UI.Button>
        </div>
      </div>
    </div>
  );
}

function GoogleG() {
  return (<svg width="18" height="18" viewBox="0 0 24 24" aria-hidden="true"><path fill="#4285F4" d="M22.5 12.2c0-.8-.1-1.4-.2-2H12v3.9h6c-.1 1-.8 2.5-2.2 3.5l-.1.1 3.2 2.5.2.1c2-1.9 3.4-4.7 3.4-8.1Z"/><path fill="#34A853" d="M12 23c2.9 0 5.3-1 7.1-2.6l-3.4-2.6c-.9.6-2.1 1.1-3.7 1.1-2.8 0-5.2-1.9-6-4.5l-.1.1-3.3 2.6-.1.1C4.2 20.4 7.8 23 12 23Z"/><path fill="#FBBC05" d="M6 14.4c-.2-.6-.3-1.3-.3-2s.1-1.4.3-2l-.1-.2L2.6 7.6l-.1.1C1.8 9 1.5 10.5 1.5 12s.3 3 1 4.3l3.5-1.9Z"/><path fill="#EA4335" d="M12 5.5c2 0 3.3.9 4.1 1.6l3-2.9C16.3 1.6 14 .5 12 .5 7.8.5 4.2 3.1 2.5 6.7l3.5 2.7c.8-2.6 3.2-3.9 6-3.9Z"/></svg>);
}
function MsLogo() {
  return (<svg width="16" height="16" viewBox="0 0 24 24" aria-hidden="true"><path fill="#F25022" d="M2 2h9.5v9.5H2z"/><path fill="#7FBA00" d="M12.5 2H22v9.5h-9.5z"/><path fill="#00A4EF" d="M2 12.5h9.5V22H2z"/><path fill="#FFB900" d="M12.5 12.5H22V22h-9.5z"/></svg>);
}

window.AuthFlow = AuthFlow;
