// /#/welcome — first-sign-in profile completion. Fires after a magic-link
// click when the user has no row in user_profiles yet. Captures who they
// are (role + company + USDOT/MC + lanes + how-they-heard) and writes to
// /api/profile-complete which auto-verifies carriers/brokers via FMCSA
// and queues the rest for editor review at /#/admin → Vetting.

const { useState: useStateW, useEffect: useEffectW } = React;

function WelcomePage({ onNav }) {
  const [user, setUser]               = useStateW(null);
  const [authChecking, setAuthChecking] = useStateW(true);
  const [role, setRole]               = useStateW("");
  const [companyName, setCompanyName] = useStateW("");
  const [usdot, setUsdot]             = useStateW("");
  const [mcNumber, setMcNumber]       = useStateW("");
  const [primaryLanes, setPrimaryLanes] = useStateW("");
  const [fleetSize, setFleetSize]     = useStateW("");
  const [hqCity, setHqCity]           = useStateW("");
  const [hqState, setHqState]         = useStateW("");
  const [howHeard, setHowHeard]       = useStateW("");
  const [useCase, setUseCase]         = useStateW("");
  const [submitting, setSubmitting]   = useStateW(false);
  const [error, setError]             = useStateW(null);
  const [done, setDone]               = useStateW(null); // { status, auto_verified }

  // Verify the user is signed in. If not, redirect to sign-in.
  useEffectW(() => {
    let cancelled = false;
    (async () => {
      try {
        const session = (window.SI_DB && window.SI_DB.auth) ? window.SI_DB.auth.readSession() : null;
        if (!session || !session.access_token) {
          if (!cancelled) {
            window.location.hash = "#/signin";
          }
          return;
        }
        // Check if profile already exists — if yes, send them to /#/account.
        const r = await fetch(`/api/profile-complete`, {
          headers: { Authorization: `Bearer ${session.access_token}` },
        });
        if (r.status === 401) {
          if (!cancelled) { window.location.hash = "#/signin"; }
          return;
        }
        const j = await r.json().catch(() => ({}));
        if (!cancelled) {
          if (j && j.profile) {
            // Already completed — bounce to account page.
            window.location.hash = "#/account";
            return;
          }
          // Pull email + uid from the session for display.
          setUser({ email: session.user?.email || "(your email)", id: session.user?.id });
          setAuthChecking(false);
        }
      } catch (e) {
        if (!cancelled) {
          setError(`Couldn't check session: ${e.message || e}`);
          setAuthChecking(false);
        }
      }
    })();
    return () => { cancelled = true; };
  }, []);

  async function submit(e) {
    e.preventDefault();
    if (submitting) return;
    setError(null);
    if (!role) { setError("Pick the role that fits you best."); return; }
    if (role === "carrier" && !usdot.trim() && !mcNumber.trim()) {
      setError(`We need your USDOT or MC number to verify carrier authority. Both are public records.`);
      return;
    }
    setSubmitting(true);
    try {
      const session = (window.SI_DB && window.SI_DB.auth) ? window.SI_DB.auth.readSession() : null;
      const r = await fetch(`/api/profile-complete`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${session.access_token}`,
        },
        body: JSON.stringify({
          role,
          company_name: companyName,
          usdot,
          mc_number: mcNumber,
          primary_lanes: primaryLanes,
          fleet_size_estimate: fleetSize,
          hq_city: hqCity,
          hq_state: hqState,
          how_heard: howHeard,
          use_case: useCase,
        }),
      });
      const j = await r.json();
      if (!r.ok) {
        setError(j.error || `HTTP ${r.status}`);
        setSubmitting(false);
        return;
      }
      setDone({ status: j.status, auto_verified: j.auto_verified });
    } catch (e) {
      setError(`${e.message || e}`);
    }
    setSubmitting(false);
  }

  if (authChecking) {
    return (
      <div style={page}>
        <div style={{ ...wrap, textAlign: "center", paddingTop: 80, opacity: 0.6 }}>Checking your session…</div>
      </div>
    );
  }

  if (done) {
    return (
      <div style={page}>
        <div style={wrap}>
          <h1 style={h1}>Welcome aboard.</h1>
          {done.auto_verified ? (
            <p style={lede}>
              Your FMCSA authority checked out — your account is <strong style={{ color: "#5fd9a8" }}>auto-verified ✓</strong>.
              You can post loads, request reach-outs, and claim entity profiles right now.
            </p>
          ) : (
            <p style={lede}>
              Your profile is in for review. We typically clear new accounts within 24 hours.
              You can browse the site freely; load posting and reach-out requests unlock once you're verified.
            </p>
          )}
          <button onClick={() => { window.location.hash = "#/account"; }} style={btnPrimary}>
            Go to my account →
          </button>
        </div>
      </div>
    );
  }

  return (
    <div style={page}>
      <div style={wrap}>
        <div style={eyebrow}>FIRST-TIME SIGN-IN · {(user && user.email) || ""}</div>
        <h1 style={h1}>Tell us who you are.</h1>
        <p style={lede}>
          We don't gate the data behind paywalls, but we do need to know who's who.
          Carriers get auto-verified against FMCSA in real time;
          the rest get a quick editor review (usually under 24 hours).
        </p>

        <form onSubmit={submit}>
          {/* Role */}
          <label style={label}>Your role</label>
          <div style={roleGrid}>
            {[
              { k: "shipper", label: "Shipper", sub: "We move freight" },
              { k: "carrier", label: "Carrier", sub: "We haul it" },
              { k: "driver",  label: "Driver",  sub: "I drive a truck" },
              { k: "press",   label: "Press / analyst", sub: "We cover the industry" },
              { k: "other",   label: "Other",   sub: "Something else" },
            ].map(opt => (
              <button
                type="button"
                key={opt.k}
                onClick={() => setRole(opt.k)}
                style={{ ...roleCard, ...(role === opt.k ? roleCardActive : {}) }}
              >
                <div style={{ fontSize: 15, fontWeight: 700 }}>{opt.label}</div>
                <div style={{ fontSize: 12, opacity: 0.65, marginTop: 4 }}>{opt.sub}</div>
              </button>
            ))}
          </div>

          {/* Company */}
          <label style={label}>Company name</label>
          <input style={input} value={companyName} onChange={(e) => setCompanyName(e.target.value)}
                 placeholder="e.g. Acme Trucking, Inc." />

          {/* USDOT/MC — required for carrier */}
          {role === "carrier" && (
            <>
              <div style={{ display: "flex", gap: 12, flexWrap: "wrap" }}>
                <div style={{ flex: 1, minWidth: 200 }}>
                  <label style={label}>USDOT #</label>
                  <input style={input} value={usdot} onChange={(e) => setUsdot(e.target.value)}
                         placeholder="e.g. 1234567" />
                </div>
                <div style={{ flex: 1, minWidth: 200 }}>
                  <label style={label}>MC # <span style={{ opacity: 0.6, fontWeight: 400 }}>(optional if USDOT given)</span></label>
                  <input style={input} value={mcNumber} onChange={(e) => setMcNumber(e.target.value)}
                         placeholder="e.g. MC-123456" />
                </div>
              </div>
              <div style={{ ...note, marginTop: 8 }}>
                We hit FMCSA QCMobile to confirm your authority is active. If it is, you're verified instantly.
              </div>
            </>
          )}

          {/* Fleet size — only for carrier */}
          {role === "carrier" && (
            <>
              <label style={label}>Fleet size <span style={{ opacity: 0.6, fontWeight: 400 }}>(optional)</span></label>
              <input style={input} type="number" min="1" value={fleetSize}
                     onChange={(e) => setFleetSize(e.target.value)}
                     placeholder="e.g. 12 trucks" />
            </>
          )}

          {/* Geography */}
          <div style={{ display: "flex", gap: 12, flexWrap: "wrap" }}>
            <div style={{ flex: 1, minWidth: 200 }}>
              <label style={label}>HQ city</label>
              <input style={input} value={hqCity} onChange={(e) => setHqCity(e.target.value)}
                     placeholder="e.g. Atlanta" />
            </div>
            <div style={{ width: 100 }}>
              <label style={label}>State</label>
              <input style={input} value={hqState} onChange={(e) => setHqState(e.target.value.toUpperCase().slice(0, 2))}
                     placeholder="GA" maxLength={2} />
            </div>
          </div>

          {/* Lanes / use case */}
          {role !== "press" && role !== "other" && (
            <>
              <label style={label}>Primary lanes <span style={{ opacity: 0.6, fontWeight: 400 }}>(optional)</span></label>
              <input style={input} value={primaryLanes} onChange={(e) => setPrimaryLanes(e.target.value)}
                     placeholder="e.g. LA → Phoenix · Chicago → Atlanta · TX intrastate" />
            </>
          )}

          <label style={label}>What brings you here?</label>
          <textarea style={{ ...input, minHeight: 70, resize: "vertical" }}
                    value={useCase} onChange={(e) => setUseCase(e.target.value)}
                    placeholder="Use case, problem you're solving, what you need from us, anything." />

          <label style={label}>How did you hear about us? <span style={{ opacity: 0.6, fontWeight: 400 }}>(optional)</span></label>
          <input style={input} value={howHeard} onChange={(e) => setHowHeard(e.target.value)}
                 placeholder="LinkedIn, a colleague, FreightWaves, etc." />

          {error && <div style={errorStyle}>{error}</div>}

          <button type="submit" disabled={submitting || !role}
                  style={{ ...btnPrimary, opacity: (submitting || !role) ? 0.55 : 1, marginTop: 24 }}>
            {submitting ? "Saving…" : "Complete profile →"}
          </button>
        </form>
      </div>
    </div>
  );
}

// --- Atoms ---
const page = {
  background: "radial-gradient(circle at 30% 0%, #1d2d52 0%, #0a1224 55%, #050913 100%)",
  minHeight: "100vh", color: "#fff",
  fontFamily: '"Helvetica Neue", Helvetica, Arial, sans-serif',
};
const wrap = { maxWidth: 720, margin: "0 auto", padding: "48px 24px 80px" };
const eyebrow = { fontSize: 11, letterSpacing: "0.32em", textTransform: "uppercase", color: "#5fa9ff", fontWeight: 600, marginBottom: 16 };
const h1   = { fontSize: 38, fontWeight: 800, letterSpacing: "-0.02em", margin: "0 0 14px" };
const lede = { fontSize: 16, lineHeight: 1.55, opacity: 0.78, margin: "0 0 36px", maxWidth: 620 };
const label = { display: "block", fontSize: 11, textTransform: "uppercase", letterSpacing: "0.08em", color: "#5fa9ff", fontWeight: 600, marginTop: 18, marginBottom: 6 };
const input = {
  width: "100%", boxSizing: "border-box", padding: "10px 14px", fontSize: 14,
  background: "rgba(255,255,255,0.06)", border: "1px solid rgba(255,255,255,0.15)",
  borderRadius: 6, color: "#fff", fontFamily: "inherit",
};
const roleGrid = {
  display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(180px, 1fr))",
  gap: 10, marginBottom: 8,
};
const roleCard = {
  padding: "14px 16px", border: "1px solid rgba(255,255,255,0.15)", borderRadius: 10,
  background: "rgba(255,255,255,0.04)", color: "#fff", textAlign: "left",
  cursor: "pointer", fontFamily: "inherit",
};
const roleCardActive = {
  borderColor: "#5fa9ff",
  background: "rgba(95,169,255,0.12)",
};
const note = { fontSize: 12, opacity: 0.6 };
const errorStyle = { marginTop: 16, padding: "10px 14px", background: "rgba(255,104,104,0.12)", border: "1px solid rgba(255,104,104,0.4)", borderRadius: 6, color: "#ff8a8a", fontSize: 13 };
const btnPrimary = {
  display: "inline-block", padding: "12px 28px", background: "#5fa9ff", color: "#0a1224",
  borderRadius: 8, border: "none", fontSize: 15, fontWeight: 700, cursor: "pointer",
  fontFamily: "inherit",
};

window.WelcomePage = WelcomePage;
