/* Quote Connect — Home screen */

const HERO_DEMOS = [
  { cat: "vehicle", item: "Toyota HiLux SR5", spec: "Diesel · Auto 4x4 · Volcanic Red",
    quotes: [{ code: "RMG", hue: 42, price: 58990 }, { code: "SSM", hue: 222, price: 60450 }, { code: "OPE", hue: 248, price: 61200 }] },
  { cat: "machinery-agricultural", item: "120hp Tractor + Loader", spec: "New · 4-in-1 · 3yr warranty",
    quotes: [{ code: "OPE", hue: 248, price: 142000 }, { code: "SSM", hue: 222, price: 148500 }] },
  { cat: "water", item: "22,500L Poly Tank ×2", spec: "Delivered + pump pre-plumbed",
    quotes: [{ code: "TET", hue: 205, price: 6840 }, { code: "MSS", hue: 32, price: 7120 }] },
];

function HeroMatch() {
  const [di, setDi] = React.useState(0);
  const [phase, setPhase] = React.useState(0); // 0 request, 1 broadcasting, 2.. quotes in, 9 done
  const demo = HERO_DEMOS[di];

  React.useEffect(() => {
    const timers = [];
    setPhase(0);
    timers.push(setTimeout(() => setPhase(1), 900));
    demo.quotes.forEach((_, i) => timers.push(setTimeout(() => setPhase(2 + i), 1700 + i * 850)));
    timers.push(setTimeout(() => setPhase(9), 1700 + demo.quotes.length * 850 + 600));
    timers.push(setTimeout(() => setDi((d) => (d + 1) % HERO_DEMOS.length), 1700 + demo.quotes.length * 850 + 3200));
    return () => timers.forEach(clearTimeout);
  }, [di]);

  const arrived = Math.max(0, phase - 1);
  const best = demo.quotes.reduce((m, q) => (q.price < m ? q.price : m), Infinity);

  return (
    <div className="hero-match card">
      <div className="hm-head">
        <span className="mono hm-id">QR-{4800 + di * 7}</span>
        <StatusPill status={phase >= 9 ? "comparing" : "live"} />
      </div>
      <div className="hm-req">
        <div className="hm-req-name display">{demo.item}</div>
        <div className="hm-req-spec mono">{demo.spec}</div>
      </div>
      <div className="hm-bcast">
        <span className={"hm-pulse" + (phase >= 1 ? " on" : "")} />
        <span className="mono">
          {phase === 0 ? "Submitting request…" : phase < 9 ? "Broadcasting to verified suppliers…" : `${demo.quotes.length} quotes in 6 min`}
        </span>
      </div>
      <div className="hm-quotes">
        {demo.quotes.map((q, i) => {
          const shown = arrived > i;
          return (
            <div key={q.code} className={"hm-quote" + (shown ? " in" : "") + (q.price === best && phase >= 9 ? " best" : "")}>
              <span className="qc-avatar mono" style={{ width: 34, height: 34, fontSize: 11,
                background: `oklch(0.93 0.04 ${q.hue})`, color: `oklch(0.42 0.13 ${q.hue})`, borderColor: `oklch(0.85 0.05 ${q.hue})` }}>{q.code}</span>
              <span className="hm-quote-meta">
                <span className="hm-quote-sup">Supplier {q.code}</span>
                <span className="qc-verified s-sm"><Icon name="badge-check" size={12} /><span className="mono">Verified</span></span>
              </span>
              <span className="hm-quote-price mono">{shown ? money(q.price) : "···"}</span>
              {q.price === best && phase >= 9 && <span className="hm-best mono">BEST</span>}
            </div>
          );
        })}
      </div>
    </div>
  );
}

function HeroSearch({ nav }) {
  const { CATEGORIES } = window.QC_DATA;
  const [q, setQ] = React.useState("");
  const [open, setOpen] = React.useState(false);
  const ql = q.trim().toLowerCase();
  const matches = ql ? CATEGORIES.filter((c) => c.name.toLowerCase().includes(ql) ||
    c.subs.some((s) => s.toLowerCase().includes(ql))).slice(0, 5) : [];
  return (
    <div className="hero-search">
      <div className="hero-search-bar">
        <Icon name="search" size={19} />
        <input
          value={q} onChange={(e) => { setQ(e.target.value); setOpen(true); }}
          onFocus={() => setOpen(true)} onBlur={() => setTimeout(() => setOpen(false), 150)}
          placeholder="What do you need a quote for?"
        />
        <Btn variant="primary" size="md" onClick={() => nav.go("browse")}>
          Get quotes <Icon name="arrow-right" size={17} />
        </Btn>
      </div>
      {open && matches.length > 0 && (
        <div className="hero-search-pop card">
          {matches.map((c) => (
            <button key={c.id} className="hero-search-opt" onMouseDown={() => nav.startQuote(c.id)}>
              <CatVisual cat={c} iconStyle="photo" size={30} radius={6} />
              <span className="hero-search-opt-name">{c.name}</span>
              <span className="mono hero-search-opt-n">{c.suppliers}</span>
              <Icon name="arrow-right" size={15} />
            </button>
          ))}
        </div>
      )}
    </div>
  );
}

const STEPS = [
  { n: "01", icon: "file-pen", t: "Describe it once", d: "Pick a category and tell us the spec. Two minutes, no account needed to start." },
  { n: "02", icon: "radio-tower", t: "We broadcast it", d: "Your request fans out to every verified supplier in that category — instantly." },
  { n: "03", icon: "git-compare-arrows", t: "Compare & choose", d: "Real quotes land in one place. Compare price, lead time and reputation. You decide." },
];

function HomeScreen({ nav, t }) {
  const { STATS, SUPPLIERS } = window.QC_DATA;
  return (
    <div className="screen home-screen">
      {/* HERO */}
      <section className="hero has-image">
        <image-slot
          id="hero-bg"
          src="https://images.unsplash.com/photo-1500382017468-9049fed747ef?w=1700&q=80&auto=format&fit=crop"
          placeholder="Drop your hero image"
          fit="cover"
        ></image-slot>
        <div className="hero-overlay" />
        <div className="qc-wrap hero-inner">
          <div className="hero-left">
            <div className="hero-eyebrow"><span className="hero-dot" /> <span className="mono">One request. Multiple quotes. · Australia-wide</span></div>
            <h1 className="display hero-h1">
              Tell us what you need.<br />Get <span className="hero-mark">real quotes</span> from verified suppliers.
            </h1>
            <p className="hero-sub">
              One request. Every supplier in the category competes for it. You compare price, lead time
              and reputation in one place — and pick the winner. Vehicles to tractors, fencing to fuel tanks.
            </p>
            <HeroSearch nav={nav} />
            <div className="hero-trust">
              {[["shield-check", "Buyers never pay"], ["badge-check", "ABN-verified suppliers"], ["timer", "First quotes within hours"]].map(([ic, l]) => (
                <span key={l} className="hero-trust-item"><Icon name={ic} size={15} /> {l}</span>
              ))}
            </div>
          </div>
          <div className="hero-right">
            <HeroMatch />
          </div>
        </div>
      </section>

      {/* HOW IT WORKS */}
      <section className="qc-wrap how">
        <div className="section-head">
          <div className="eyebrow">How it works</div>
          <h2 className="display section-title">From request to real quotes in three moves.</h2>
        </div>
        <div className="how-grid">
          {STEPS.map((s) => (
            <div key={s.n} className="how-card card">
              <div className="how-card-top">
                <span className="how-n mono">{s.n}</span>
                <span className="how-ic"><Icon name={s.icon} size={22} stroke={1.75} /></span>
              </div>
              <h3 className="how-t display">{s.t}</h3>
              <p className="how-d">{s.d}</p>
            </div>
          ))}
        </div>
      </section>

      {/* CATEGORIES */}
      <section className="qc-wrap home-cats">
        <div className="section-head row">
          <div>
            <div className="eyebrow">Categories</div>
            <h2 className="display section-title">20 categories. One way to buy.</h2>
          </div>
          <Btn variant="outline" onClick={() => nav.go("browse")}>Browse all <Icon name="arrow-right" size={16} /></Btn>
        </div>
        <CategorySection iconStyle={t.icons} onQuote={nav.startQuote} limit={8} compact />
      </section>

      {/* TRUST */}
      <section className="trust-band">
        <div className="qc-wrap trust-inner">
          <div className="trust-copy">
            <div className="eyebrow">The verified difference</div>
            <h2 className="display section-title">Every supplier is checked before they can quote you.</h2>
            <ul className="trust-list">
              {[["building-2", "ABN & business identity verified", "We confirm a real, registered Australian business behind every account."],
                ["star", "Reputation that follows them", "Ratings and response times are earned across every quote — and shown to you."],
                ["lock", "Your details stay protected", "Suppliers see your request, not your inbox. You choose who to talk to."]].map(([ic, h, d]) => (
                <li key={h} className="trust-li">
                  <span className="trust-li-ic"><Icon name={ic} size={18} /></span>
                  <div><b>{h}</b><span>{d}</span></div>
                </li>
              ))}
            </ul>
            <Btn variant="dark" size="lg" onClick={() => nav.go("supplier")}>See the supplier side <Icon name="arrow-right" size={17} /></Btn>
          </div>
          <div className="trust-cards">
            {SUPPLIERS.slice(0, 3).map((s, i) => (
              <div key={s.id} className={"trust-sup card lift-" + i}>
                <div className="trust-sup-top">
                  <SupAvatar sup={s} size={44} />
                  <div className="trust-sup-id">
                    <div className="trust-sup-name">{s.name}</div>
                    <div className="mono trust-sup-loc"><Icon name="map-pin" size={12} /> {s.loc}</div>
                  </div>
                </div>
                <div className="trust-sup-meta">
                  <Verified size="sm" />
                  <Stars rating={s.rating} reviews={s.reviews} />
                </div>
                <div className="trust-sup-foot mono">ABN {s.abn} · since {s.since} · {s.resp}</div>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* CTA */}
      <section className="qc-wrap">
        <div className="cta card">
          <div className="cta-bg" />
          <div className="cta-inner">
            <h2 className="display cta-h">Got something to buy?<br />Submit a quote request today — it’s free.</h2>
            <p className="cta-sub">Start a request now. You’ll have competing quotes before you’ve finished your coffee.</p>
            <div className="cta-actions">
              <Btn variant="primary" size="lg" onClick={() => nav.go("browse")}>Start a request <Icon name="arrow-right" size={18} /></Btn>
              <Btn variant="ghost" size="lg" onClick={() => nav.go("buyer")}>Track my quotes</Btn>
            </div>
          </div>
        </div>
      </section>
    </div>
  );
}

Object.assign(window, { HomeScreen });
