/* ============================================================
   Carzello — public landing (ADESA-style) + sign-in (iCloud-style)
   Full-screen screens rendered outside the buyer app chrome
   (route.name "home" and "signin" in app.jsx).
   ============================================================ */

const HOME_MAKE_INITIALS = { TOYOTA: "TO", LEXUS: "LX", "MERCEDES-BENZ": "MB", NISSAN: "NI", FORD: "FO", HONDA: "HO", JEEP: "JE", CHEVROLET: "CH", GMC: "GM", BMW: "BM", HYUNDAI: "HY", KIA: "KI", DODGE: "DO", TESLA: "TE", AUDI: "AU" };
const homeSlug = (s) => String(s).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/(^-|-$)/g, "");

/* Public on this page: the lots, the car popup and the /cars catalog (make tiles, model chips).
   The marketplace (#/browse) needs a signed-in account, so for a signed-out visitor its links go
   through sign-in first and land there afterwards. q = the Copart tab's starting search. */
const HOME_BROWSE = "/#/browse";
function homeCopartUrl(q) {
  const p = new URLSearchParams({ tab: "copart" });
  if (q) p.set("q", q);
  return "/?" + p.toString() + "#/browse";
}
// model chips → each model's public catalog page (server-rendered, with its current lots)
const HOME_CHIPS = [
  ["Toyota Land Cruiser", "/cars/toyota/land-cruiser"],
  ["Lexus LX", "/cars/lexus/lx"],
  ["Mercedes-Benz G-Class", "/cars/mercedes-benz/g-class"],
  ["Nissan Armada (Patrol)", "/cars/nissan/armada"],
  ["Ford F-150", "/cars/ford/f-150"],
];

/* A real Copart lot. variant: "hero" (big showcase), "mini" (small stacked), default grid card.
   Uses the Copart module's helpers so names, photos and dates match the Copart tab exactly.
   A plain click opens the car popup right here (public details, no sign-in); the href is that
   same popup as a URL — new tab, copied link, no JS. */
function HomeLot({ v, variant }) {
  const title = `${v.year || ""} ${titleCaseWord(v.make)} ${titleCaseWord(copartModel(v))}`.trim();
  const sale = copartSale(v);
  const upcoming = sale && sale.inDays >= 0;          // never present a passed sale date as upcoming
  const soon = upcoming && sale.inDays <= 2;
  const when = upcoming ? (sale.inDays === 0 ? "Today" : sale.inDays === 1 ? "Tomorrow" : sale.short) : "Request quote";
  const retail = Number(v.estRetailValue) || 0;
  const mini = variant === "mini";
  const cls = variant === "hero" ? "lot home-card-a" : mini ? "lot home-card-b" : "lot home-lot";
  const open = (e) => {
    if (e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return; // new tab / window: the browser's job
    e.preventDefault();
    openCopartLot(v);
  };
  return (
    <a className={cls} href={`/?lot=${encodeURIComponent(v.lotNumber)}#/home`} onClick={open} aria-label={`${title}, lot ${v.lotNumber}`}>
      <div className="hl-photo">
        <CopartHeroImg v={v} />
        <span className="hl-tag"><Pill kind="red" style={{ fontSize: 9.5 }}>Copart</Pill></span>
      </div>
      {!mini && <>
        <h3>{title}</h3>
        <div className="sub">{Number(v.odometer || 0).toLocaleString("en-US")} mi · {titleCaseWord(v.damageDescription) || "—"}</div>
      </>}
      <div className="foot" style={mini ? { border: 0, marginTop: 10, paddingTop: 0 } : undefined}>
        <div><div className="k">Est. retail</div><div className="price tnum" style={mini ? { fontSize: 18 } : undefined}>{retail ? fmtUSD(retail) : "—"}</div></div>
        <span style={{ textAlign: "right" }}>
          <div className="k">{upcoming ? "Auction" : "Sourcing"}</div>
          <div className="tnum" style={{ fontWeight: 800, fontSize: 13, color: soon ? "var(--brand)" : "var(--fg-2)" }}>{when}</div>
        </span>
      </div>
    </a>
  );
}
function titleCaseWord(s) { return String(s || "").toLowerCase().replace(/\b\w/g, (c) => c.toUpperCase()); }

/* Where the lot cards would be when there are none to show — never placeholder lots: the feed
   didn't answer ("error", with Try again) or had nothing to feature ("empty"). hero = the
   showcase slot. browse = the marketplace link's props (sign-in first for a signed-out visitor). */
function HomeGate({ kind, hero, onRetry, browse }) {
  const error = kind === "error";
  return (
    <div className={"home-gate" + (hero ? " home-gate-hero" : "")}>
      <span className="hg-ic"><I.car width="20" height="20" /></span>
      <div className="hg-txt">
        <h3>{error ? "Today's lots couldn't load" : "No featured lots right now"}</h3>
        <p>{error ? "The live feed didn't answer — try again, or open the full catalog." : "Open the full catalog to see every lot in the live feed."}</p>
      </div>
      <div className="hg-acts">
        {error && onRetry && <button type="button" className="btn primary" onClick={onRetry}>Try again</button>}
        <a className={"btn " + (error ? "outline" : "primary")} {...browse}>Browse vehicles</a>
      </div>
    </div>
  );
}

function Home() {
  const acct = useAccount();
  const user = acct.user;
  const guest = !user && acct.status === "guest"; // signed out for sure (not just still checking)
  const [makes, setMakes] = useState(null);
  const [total, setTotal] = useState(null);
  const [lots, setLots] = useState([]);
  const [lotsState, setLotsState] = useState("loading"); // loading | ready | empty | error
  const [lotsEyebrow, setLotsEyebrow] = useState("From the auction feed");
  const [retry, setRetry] = useState(0);
  const [q, setQ] = useState("");
  useEffect(() => {
    // every figure on this page comes from the live dataset — no hardcoded counts (public aggregates)
    fetch("/api/copart/status").then((r) => r.json()).then((d) => { if (d && d.total) setTotal(d.total); }).catch(() => {});
    fetch("/api/copart/facets").then((r) => r.json()).then((d) => setMakes(d.success ? d.makes.slice(0, 8) : [])).catch(() => setMakes([]));
  }, []);
  useEffect(() => {
    // the featured lots are public and the same for every visitor: the server picks them (auctioning
    // in the next 14 days when there are enough, else the curated feed) and says which in `eyebrow`
    let dead = false;
    setLotsState("loading");
    fetch("/api/copart/featured")
      .then((r) => r.json())
      .then((d) => {
        if (!d || d.success !== true || !Array.isArray(d.data)) throw new Error("feed unavailable");
        const rows = d.data.filter((v) => v && v.lotNumber != null).slice(0, 6);
        if (dead) return;
        setLots(rows);
        setLotsEyebrow(typeof d.eyebrow === "string" && d.eyebrow.trim() ? d.eyebrow.trim() : "From the auction feed");
        setLotsState(rows.length ? "ready" : "empty");
      })
      .catch(() => { if (!dead) setLotsState("error"); });
    return () => { dead = true; };
  }, [retry]);
  const totalLabel = total ? total.toLocaleString("en-US") : "140,000";
  const showLots = lotsState === "ready";
  // the feed failed / had nothing → say so (no endless skeleton)
  const gateKind = lotsState === "error" || lotsState === "empty" ? lotsState : null;
  const retryLots = () => setRetry((n) => n + 1);
  // the landing page is never a return target — after sign-in buyers land in the marketplace
  const toSignIn = (mode) => (e) => { e.preventDefault(); goSignIn(null, mode ? { mode } : undefined); };
  // marketplace links: plain links when signed in; a signed-out visitor signs in first, then lands on the same target
  const gate = (target) => ({ href: target, onClick: (e) => { if (!guest) return; e.preventDefault(); goSignIn(target); } });
  function search(e) {
    e.preventDefault();
    const target = homeCopartUrl(q.trim().slice(0, 100));
    if (guest) goSignIn(target); else location.assign(target);
  }

  return (
    <div className="home">
      <header className="home-nav"><div className="home-wrap in">
        <a className="wordmark" href="#/home"><img className="logo-img" src="assets/carzello-logo.svg" alt="Carzello" style={{ height: 30 }} /></a>
        <nav className="hide-sm">
          <a {...gate(HOME_BROWSE)}>Buy vehicles</a>
          <a href="#/consignor">Sell / consign</a>
          <a href="#/help">How it works</a>
        </nav>
        <div className="acts">
          {user
            ? <a className="btn primary" href="#/browse">Enter marketplace →</a>
            : <><a className="btn ghost hide-sm" href="#/signin" onClick={toSignIn()}>Sign in</a><a className="btn primary" href="#/signin" onClick={toSignIn("signup")}>Create account</a></>}
        </div>
      </div></header>

      <section className="home-hero"><div className="blob" /><div className="home-wrap in">
        <div>
          <span className="eyebrow">Wholesale vehicle marketplace</span>
          <h1 style={{ marginTop: 14 }}>Auction cars, <span className="r">sourced and shipped</span> to your door.</h1>
          <p className="lead">Graded, condition-guaranteed vehicles from our own inventory plus {totalLabel}+ live Copart US lots — we inspect, bid on your behalf, and deliver landed-cost to the GCC &amp; Central Asia.</p>
          <form className="home-search" onSubmit={search}>
            <I.search width="20" height="20" />
            <input placeholder="Search make, model, VIN or lot #" aria-label="Search inventory" maxLength={100} value={q} onChange={(e) => setQ(e.target.value)} />
            <button className="btn primary" type="submit">Search</button>
          </form>
          <div className="home-chips">
            {HOME_CHIPS.map(([label, href]) => <a key={label} href={href}>{label}</a>)}
          </div>
        </div>
        <div className={"home-visual" + (gateKind ? " gated" : "")}>
          <div className="ring" />
          {showLots
            ? <><HomeLot v={lots[0]} variant="hero" />{lots[1] && <HomeLot v={lots[1]} variant="mini" />}</>
            : gateKind ? <HomeGate kind={gateKind} hero onRetry={retryLots} browse={gate(homeCopartUrl())} />
            : <div className="lot home-card-a hl-skel" aria-hidden="true" />}
        </div>
      </div></section>

      <div className="home-stats"><div className="home-wrap in">
        <div className="stat"><div className="n tnum">{totalLabel}</div><div className="l">Live lots</div></div>
        <div className="stat"><div className="n tnum">{SHIP_DEST.length}</div><div className="l">Delivery ports</div></div>
        <div className="stat"><div className="n">48h</div><div className="l">Arbitration</div></div>
        <div className="stat"><div className="n">0–5</div><div className="l">AutoGrade on every car</div></div>
      </div></div>

      <section className="home-sec"><div className="home-wrap">
        <div className="home-head"><div><span className="eyebrow">Shop by make</span><h2 style={{ marginTop: 8 }}>Browse the catalog</h2><p>Every make from the live auction feed, graded and priced to your port.</p></div><a className="btn ghost" {...gate(HOME_BROWSE)}>View all inventory</a></div>
        {!makes && <div className="muted" style={{ padding: "18px 0" }}>Loading the catalog…</div>}
        <div className="home-makes">
          {(makes || []).map((m) => (
            <a className="make" key={m.v} href={`/cars/${homeSlug(m.v)}`}>
              <span className="ic">{HOME_MAKE_INITIALS[m.v] || m.v.slice(0, 2)}</span>
              <div><div className="nm">{titleCaseWord(m.v)}</div><div className="ct">{m.c.toLocaleString("en-US")} lots</div></div>
            </a>
          ))}
        </div>
      </div></section>

      <section className="home-sec alt"><div className="home-wrap">
        <div className="home-head"><div><span className="eyebrow">How it works</span><h2 style={{ marginTop: 8 }}>From the auction block to your port</h2></div></div>
        <div className="home-steps">
          <div className="step"><div className="no">STEP 01</div><h3>Browse &amp; bid</h3><p>Search Carzello's graded stock and 146,000+ Copart lots. Set a proxy max or request a sourcing quote on any vehicle.</p></div>
          <div className="step"><div className="no">STEP 02</div><h3>We inspect &amp; win it</h3><p>Our team inspects, confirms the AutoGrade condition report, and bids on your behalf at the US auction.</p></div>
          <div className="step"><div className="no">STEP 03</div><h3>Delivered landed-cost</h3><p>Door-to-port logistics, duty and freight included — one transparent price to {SHIP_DEST.map((d) => d.label.split(" · ")[1]).join(", ")}.</p></div>
        </div>
      </div></section>

      <section className="home-sec"><div className="home-wrap">
        <div className="home-head"><div><span className="eyebrow">Why Carzello</span><h2 style={{ marginTop: 8 }}>Built for cross-border buyers</h2></div></div>
        <div className="home-vp">
          {[["shield", "AutoGrade guarantee", "Every lot inspected and graded 0–5, with a condition report you can trust before you bid."],
            ["offer", "Landed-cost pricing", "Buyer fee, freight, duty and VAT shown up front — the real price to your door, no surprises."],
            ["clock", "48-hour arbitration", "If a delivered car doesn't match its report, you have a 48-hour window to file a claim."],
            ["truck", "146k+ Copart lots", "The full US salvage & wholesale feed, refreshed daily — sourced for you on request."]].map(([ic, h, p]) => (
            <div className="vp" key={h}><div className="vpic">{I[ic]({ width: 20, height: 20 })}</div><h3>{h}</h3><p>{p}</p></div>
          ))}
        </div>
      </div></section>

      <section className="home-sec"><div className="home-wrap">
        <div className="home-head"><div><span className="eyebrow">{showLots ? lotsEyebrow : "From the auction feed"}</span><h2 style={{ marginTop: 8 }}>Featured lots</h2></div><a className="btn ghost" {...gate(HOME_BROWSE)}>See all</a></div>
        {showLots
          ? <div className="home-lots">{lots.map((v) => <HomeLot key={v.lotNumber} v={v} />)}</div>
          : gateKind ? <HomeGate kind={gateKind} onRetry={retryLots} browse={gate(homeCopartUrl())} />
          : <div className="muted" style={{ padding: "30px 0" }}>Loading live inventory…</div>}
      </div></section>

      <section className="home-sec" style={{ paddingTop: 0 }}><div className="home-wrap">
        <div className="home-cta">
          <div><h2>Ready to bid?</h2><p>Create an account, fund your deposit, and start winning cars today.</p></div>
          <div style={{ display: "flex", gap: 10, flexWrap: "wrap" }}><a className="btn primary lg" href="#/signin" onClick={toSignIn("signup")}>Create account</a><a className="btn ghost lg" href="#/help">Talk to us</a></div>
        </div>
      </div></section>

      <Footer />
    </div>
  );
}

/* ---------- iCloud-style sign-in ---------- */
function SignIn() {
  const acct = useAccount();
  // "Create account" links ask for sign-up mode via sessionStorage (read once, then cleared)
  const [mode, setMode] = useState(() => { try { return sessionStorage.getItem("carzello.signinMode") === "signup" ? "signup" : "signin"; } catch (e) { return "signin"; } });
  useEffect(() => { try { sessionStorage.removeItem("carzello.signinMode"); } catch (e) {} }, []);
  const [email, setEmail] = useState("");
  const [pw, setPw] = useState("");
  const [name, setName] = useState("");
  const [company, setCompany] = useState("");
  const [phone, setPhone] = useState("");
  const [busy, setBusy] = useState(false);
  const [err, setErr] = useState(null);
  const [ok, setOk] = useState(null);
  function submit(e) {
    e.preventDefault();
    if (busy) return;
    setErr(null); setOk(null);
    if (!FB.enabled) { setErr("Sign-in is unavailable right now — please try again shortly."); return; }
    if (mode === "signup" && !name.trim()) { setErr("Enter your full name."); return; }
    setBusy(true);
    // back to where the visitor started (e.g. the same car), replacing this page in history.
    // Sessions last until "Sign out" (one sign-in shared by every tab); the reload is ours, so no stale-tab notice meanwhile.
    const enter = () => FB.adoptAccountState().then(() => returnAfterSignIn());
    const p = mode === "signin" ? leavingTab(FB.signIn(email, pw).then(enter))
      : mode === "signup" ? leavingTab(FB.signUp(email, pw, { name: name.trim(), company: company.trim(), phone: phone.trim() }).then(enter))
      : FB.resetPassword(email).then(() => { setOk("Password reset email sent — check your inbox."); setBusy(false); });
    p.catch((er) => { setErr((er && er.message) || "Something went wrong. Try again."); setBusy(false); });
  }
  // "/#/home" (not "#/home") drops a ?lot= carried in from a car popup
  const logo = <a className="wordmark" href="/#/home" style={{ justifyContent: "center", fontSize: 21, marginBottom: 20 }}><img src="assets/carzello-logo.svg" alt="Carzello" style={{ height: 26 }} /></a>;
  const backHome = <p style={{ textAlign: "center", marginTop: 16 }}><a href="/#/home" style={{ color: "var(--fg-3)", fontSize: 13, fontWeight: 600 }}>← Back to carzello.com</a></p>;

  // already signed in (e.g. Back into this page): offer to continue — never auto-redirect (would trap Back)
  if (acct.user && !busy) return (
    <div className="signin"><div className="aura" />
      <div className="signin-col">
        <div className="signin-box">
          {logo}
          <h1>You're signed in</h1>
          <p className="hint" style={{ overflowWrap: "anywhere" }}>Signed in as <b>{acct.user.email}</b></p>
          {err && <div className="feedback err" role="alert" style={{ marginTop: 14 }}><I.alert width="13" height="13" />{err}</div>}
          <button className="btn primary lg block" style={{ marginTop: 18 }} onClick={() => returnAfterSignIn()}>Continue</button>
          <button className="btn outline lg block" style={{ marginTop: 10 }} onClick={() => leavingTab(FB.signOut())}>Sign out</button>
        </div>
        {backHome}
      </div>
    </div>
  );

  const title = mode === "signin" ? "Sign in" : mode === "signup" ? "Create your account" : "Reset password";
  return (
    <div className="signin"><div className="aura" />
      <div className="signin-col">
        <div className="signin-box">
          {logo}
          <h1>{title}</h1>
          <p className="hint">{mode === "reset" ? "We'll email you a link to set a new password."
            : mode === "signup" ? "New accounts are reviewed by our team before bidding opens — you can browse right away. We'll email you a link to verify your address."
            : "Use your Carzello account to bid, track orders, and manage payouts."}</p>
          <form onSubmit={submit}>
            {mode === "signup" && <>
              <div className="sfield"><input placeholder="Full name" required maxLength={100} value={name} onChange={(e) => setName(e.target.value)} autoComplete="name" aria-label="Full name" /></div>
              <div className="sfield"><input placeholder="Company (optional)" maxLength={120} value={company} onChange={(e) => setCompany(e.target.value)} autoComplete="organization" aria-label="Company (optional)" /></div>
              <div className="sfield"><input type="tel" placeholder="Phone / WhatsApp (optional)" maxLength={40} value={phone} onChange={(e) => setPhone(e.target.value)} autoComplete="tel" aria-label="Phone or WhatsApp (optional)" /></div>
            </>}
            <div className="sfield"><input type="email" placeholder="Email" required value={email} onChange={(e) => setEmail(e.target.value)} autoComplete="email" aria-label="Email" /></div>
            {mode !== "reset" && (
              <div className="sfield">
                <input type="password" placeholder="Password" required minLength={8} value={pw} onChange={(e) => { setPw(e.target.value); setErr(null); }} autoComplete={mode === "signup" ? "new-password" : "current-password"} aria-label="Password" />
                <button className="go" type="submit" aria-label="Continue"><svg width="16" height="16" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="2"><path d="M4 8h8M9 4l4 4-4 4" /></svg></button>
              </div>
            )}
            {mode === "signin" && (
              <div className="srow" style={{ justifyContent: "center" }}>
                <a onClick={(e) => { e.preventDefault(); setErr(null); setMode("reset"); }} href="#">Forgot password?</a>
              </div>
            )}
            {err && <div className="feedback err" role="alert" style={{ marginTop: 14 }}><I.alert width="13" height="13" />{err}</div>}
            {ok && <div className="feedback ok" role="status" style={{ marginTop: 14 }}><I.check width="13" height="13" />{ok}</div>}
            <button className="btn primary lg block" type="submit" disabled={busy} style={{ marginTop: 18 }}>{busy ? "Please wait…" : mode === "signin" ? "Sign in" : mode === "signup" ? "Create account" : "Send reset email"}</button>
          </form>
          {mode === "signin"
            ? <><div className="signin-sep">New to Carzello?</div><div className="signin-create">Don't have an account? <a onClick={(e) => { e.preventDefault(); setErr(null); setOk(null); setMode("signup"); }} href="#">Create yours</a></div></>
            : <div className="signin-create" style={{ marginTop: 18 }}><a onClick={(e) => { e.preventDefault(); setErr(null); setOk(null); setMode("signin"); }} href="#">← Back to sign in</a></div>}
        </div>
        <p className="signin-legal">This is a private marketplace for registered dealers and buyers. By signing in you agree to the Terms of Sale and Privacy Notice.</p>
        {backHome}
      </div>
    </div>
  );
}

Object.assign(window, { Home, SignIn });
