// onboarding.jsx — signup / first number / prepay

const FUND_AMOUNTS = [50, 100, 250, 500];

function Onboarding({ onComplete }) {
  const [step, setStep] = React.useState(0);
  const steps = ["Account", "Workspace", "Number", "Fund"];

  // Form state — collected across steps, submitted at end of step 1
  const [email, setEmail] = React.useState("");
  const [password, setPassword] = React.useState("");
  const [fullName, setFullName] = React.useState("");
  const [workspaceName, setWorkspaceName] = React.useState("");
  const [workspaceType, setWorkspaceType] = React.useState("agency");

  // Created workspace after signup (used by steps 2 & 3)
  const [createdWorkspaceId, setCreatedWorkspaceId] = React.useState(null);

  // Inventory + selection
  const [suggestions, setSuggestions] = React.useState([]);
  const [selectedInventoryId, setSelectedInventoryId] = React.useState(null);
  const [loadingSuggestions, setLoadingSuggestions] = React.useState(false);

  // Funding
  const [fundAmount, setFundAmount] = React.useState(100);

  // Status
  const [submitting, setSubmitting] = React.useState(false);
  const [error, setError] = React.useState(null);

  function clearError() { setError(null); }

  async function submitSignup() {
    if (!email || !password || !fullName || !workspaceName) {
      setError("Fill in all fields"); return;
    }
    setSubmitting(true); setError(null);
    try {
      const res = await API.auth.signup({ email, password, fullName, workspaceName });
      API.setToken(res.data.accessToken);
      setCreatedWorkspaceId(res.data.workspace.id);
      // If user picked 'client' but signup creates 'agency' by default, patch it.
      if (workspaceType === "client") {
        try { await API.workspaces.update(res.data.workspace.id, { name: workspaceName }); } catch {}
      }
      // Load number suggestions for step 2
      await loadSuggestions();
      setStep(2);
    } catch (err) {
      setError(err.message || "Sign-up failed");
    } finally {
      setSubmitting(false);
    }
  }

  async function loadSuggestions() {
    setLoadingSuggestions(true);
    try {
      const res = await API.inventory.suggestions(3);
      setSuggestions(res.data || []);
      if (res.data && res.data.length) setSelectedInventoryId(res.data[0].id);
    } catch (err) {
      setError(err.message || "Could not load number suggestions");
    } finally {
      setLoadingSuggestions(false);
    }
  }

  async function claimNumber() {
    if (!selectedInventoryId) { setError("Pick a number"); return; }
    setSubmitting(true); setError(null);
    try {
      await API.onboarding.number({
        workspaceId: createdWorkspaceId,
        inventoryId: selectedInventoryId,
      });
      setStep(3);
    } catch (err) {
      setError(err.message || "Could not claim number");
    } finally {
      setSubmitting(false);
    }
  }

  async function fundWallet(skip) {
    setSubmitting(true); setError(null);
    try {
      if (!skip) {
        await API.onboarding.fund({
          workspaceId: createdWorkspaceId,
          amountCents: fundAmount * 100,
          paymentMethodId: "dev-skip",
        });
      }
      onComplete && onComplete();
    } catch (err) {
      setError(err.message || "Could not complete top-up");
      setSubmitting(false);
    }
  }

  function formatNumber(num) {
    if (!num) return "";
    const m = String(num).match(/^\+1(\d{3})(\d{3})(\d{4})$/);
    return m ? `(${m[1]}) ${m[2]}-${m[3]}` : num;
  }

  return (
    <div className="onboarding">
      <div className="onboarding-card">
        <div style={{display:"flex", alignItems:"center", justifyContent:"center", gap:10, marginBottom:28}}>
          <div style={{width:30, height:30, borderRadius:8, background:"linear-gradient(135deg,#0A84FF,#9333EA)", color:"white", fontSize:14, fontWeight:700, display:"grid", placeItems:"center"}}>C</div>
          <div style={{fontFamily:"var(--serif)", fontSize:20}}>Call tracking</div>
        </div>

        <div className="stepper">
          {steps.map((s, i) => (
            <span key={s} className={i < step ? "done" : i === step ? "on" : ""}/>
          ))}
        </div>

        {step === 0 && (
          <div className="col g16" style={{animation:"fadeSlide .24s"}}>
            <div style={{textAlign:"center"}}>
              <h1 className="serif" style={{fontSize:32, letterSpacing:"-0.015em", marginBottom:6, fontWeight:400}}>Create your account</h1>
              <div style={{color:"var(--ink-3)", fontSize:14}}>No credit card · free to explore · pay only for what you use</div>
            </div>
            <div className="field"><label>Your name</label>
              <input className="input" placeholder="Jordan Chen" value={fullName} onChange={(e) => { setFullName(e.target.value); clearError(); }}/>
            </div>
            <div className="field"><label>Work email</label>
              <input className="input" type="email" placeholder="you@agency.com" value={email} onChange={(e) => { setEmail(e.target.value); clearError(); }}/>
            </div>
            <div className="field"><label>Password</label>
              <input className="input" type="password" placeholder="8+ characters" value={password} onChange={(e) => { setPassword(e.target.value); clearError(); }}/>
            </div>
            {error && <div style={{fontSize:12.5, color:"#DC2626", background:"rgba(220,38,38,.08)", padding:"8px 10px", borderRadius:7, textAlign:"center"}}>{error}</div>}
            <button className="btn btn-primary btn-lg" onClick={() => {
              if (!email || !password || !fullName) { setError("Fill in all fields"); return; }
              if (password.length < 8) { setError("Password must be at least 8 characters"); return; }
              clearError();
              setStep(1);
            }}>Continue</button>
            <div style={{fontSize:11.5, color:"var(--ink-4)", textAlign:"center"}}>By signing up you agree to our Terms and Privacy Policy</div>
          </div>
        )}

        {step === 1 && (
          <div className="col g16" style={{animation:"fadeSlide .24s"}}>
            <div style={{textAlign:"center"}}>
              <h1 className="serif" style={{fontSize:32, letterSpacing:"-0.015em", marginBottom:6, fontWeight:400}}>Name your workspace</h1>
              <div style={{color:"var(--ink-3)", fontSize:14}}>You can add more workspaces for clients later</div>
            </div>
            <div className="field"><label>Workspace name</label>
              <input className="input" placeholder="Bluebird Marketing" value={workspaceName} onChange={(e) => { setWorkspaceName(e.target.value); clearError(); }}/>
            </div>
            <div className="field"><label>I'm setting this up for</label>
              <div style={{display:"grid", gridTemplateColumns:"1fr 1fr", gap:8}}>
                {[
                  { id: "agency", label: "My agency" },
                  { id: "client", label: "One business" },
                ].map((opt) => {
                  const active = workspaceType === opt.id;
                  return (
                    <div key={opt.id}
                      onClick={() => setWorkspaceType(opt.id)}
                      style={{padding:"14px", borderRadius:"var(--radius)", border: active ? "1.5px solid var(--accent)" : ".5px solid var(--line-2)", background: active ? "var(--accent-soft)" : "var(--bg-elev)", textAlign:"center", fontWeight:500, fontSize:13.5, cursor:"pointer"}}>
                      {opt.label}
                    </div>
                  );
                })}
              </div>
            </div>
            {error && <div style={{fontSize:12.5, color:"#DC2626", background:"rgba(220,38,38,.08)", padding:"8px 10px", borderRadius:7, textAlign:"center"}}>{error}</div>}
            <button className="btn btn-primary btn-lg" onClick={submitSignup} disabled={submitting}>
              {submitting ? "Creating account…" : "Create account & continue"}
            </button>
            <button className="btn btn-ghost btn-sm" onClick={() => { clearError(); setStep(0); }} disabled={submitting}>Back</button>
          </div>
        )}

        {step === 2 && (
          <div className="col g16" style={{animation:"fadeSlide .24s"}}>
            <div style={{textAlign:"center"}}>
              <h1 className="serif" style={{fontSize:32, letterSpacing:"-0.015em", marginBottom:6, fontWeight:400}}>Claim your first number</h1>
              <div style={{color:"var(--ink-3)", fontSize:14}}>Here are 3 handpicked for you · instant</div>
            </div>
            {loadingSuggestions && <div style={{textAlign:"center", color:"var(--ink-4)", fontSize:13, padding:"20px 0"}}>Loading suggestions…</div>}
            {!loadingSuggestions && suggestions.length === 0 && (
              <div style={{textAlign:"center", color:"var(--ink-4)", fontSize:13, padding:"20px 0"}}>No numbers available right now.</div>
            )}
            {!loadingSuggestions && suggestions.map((r, i) => {
              const active = selectedInventoryId === r.id;
              return (
                <div key={r.id}
                  onClick={() => setSelectedInventoryId(r.id)}
                  style={{padding:"14px 18px", borderRadius:"var(--radius)", background:"var(--bg-elev)", border: active ? "1.5px solid var(--accent)" : ".5px solid var(--line-2)", display:"flex", alignItems:"center", gap:12, cursor:"pointer"}}>
                  <input type="radio" name="num" checked={active} readOnly style={{accentColor:"var(--accent)"}}/>
                  <div style={{flex:1}}>
                    <div className="num serif" style={{fontSize:20}}>{formatNumber(r.number)}</div>
                    <div className="muted" style={{fontSize:12}}>
                      {r.vanityPattern ? `Vanity · ${r.vanityPattern}` : r.isMemorable ? "Memorable digits" : `Toll-free · ${r.prefix}`}
                    </div>
                  </div>
                  <span className="pill good"><span className="dot"/>$2/mo</span>
                </div>
              );
            })}
            {error && <div style={{fontSize:12.5, color:"#DC2626", background:"rgba(220,38,38,.08)", padding:"8px 10px", borderRadius:7, textAlign:"center"}}>{error}</div>}
            <button className="btn btn-primary btn-lg" onClick={claimNumber} disabled={submitting || !selectedInventoryId}>
              {submitting ? "Claiming…" : "Claim & continue"}
            </button>
            <button className="btn btn-ghost btn-sm" onClick={() => { clearError(); setStep(3); }} disabled={submitting}>Skip · I'll set up numbers later</button>
          </div>
        )}

        {step === 3 && (
          <div className="col g16" style={{animation:"fadeSlide .24s"}}>
            <div style={{textAlign:"center"}}>
              <h1 className="serif" style={{fontSize:32, letterSpacing:"-0.015em", marginBottom:6, fontWeight:400}}>Fund your wallet</h1>
              <div style={{color:"var(--ink-3)", fontSize:14}}>Prepay, no contracts · inbound $0.032/min · outbound $0.009/min</div>
            </div>
            <div style={{padding:"16px", background:"var(--bg-sunken)", borderRadius:"var(--radius)", fontSize:13, color:"var(--ink-3)", lineHeight:1.6}}>
              $100 ≈ <strong style={{color:"var(--ink)"}}>3,000 inbound minutes</strong> or about <strong style={{color:"var(--ink)"}}>750 calls</strong> at a 4-min average.
            </div>
            <div className="field"><label>Top up</label>
              <div className="row g8">
                {FUND_AMOUNTS.map((a) => {
                  const active = fundAmount === a;
                  return (
                    <div key={a}
                      onClick={() => setFundAmount(a)}
                      style={{flex:1, padding:"12px", borderRadius:"var(--radius)", border: active ? "1.5px solid var(--accent)" : ".5px solid var(--line-2)", background: active ? "var(--accent-soft)" : "var(--bg-elev)", textAlign:"center", cursor:"pointer"}}>
                      <div className="serif" style={{fontSize:22}}>${a}</div>
                      {a === 100 && <div style={{fontSize:10, color:"var(--accent)", fontWeight:600, letterSpacing:".05em"}}>POPULAR</div>}
                    </div>
                  );
                })}
              </div>
            </div>
            <div style={{fontSize:11.5, color:"var(--ink-4)", textAlign:"center", padding:"4px 0"}}>
              In dev, top-ups credit instantly without a real card.
            </div>
            {error && <div style={{fontSize:12.5, color:"#DC2626", background:"rgba(220,38,38,.08)", padding:"8px 10px", borderRadius:7, textAlign:"center"}}>{error}</div>}
            <button className="btn btn-primary btn-lg" onClick={() => fundWallet(false)} disabled={submitting}>
              {submitting ? "Processing…" : `Fund $${fundAmount} & enter dashboard`}
            </button>
            <button className="btn btn-ghost btn-sm" onClick={() => fundWallet(true)} disabled={submitting}>Skip · I'll add funds later</button>
          </div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { Onboarding });
