// Homepage — search, map, featured cities, insights

const { useState: useStateH, useEffect: useEffectH, useRef: useRefH, useMemo: useMemoH } = React;

// =============================================================================
// AIR HORN — easter egg on truck click. Pure Web Audio synth (no audio file).
// =============================================================================
let _audioCtx = null;
function honkAirHorn() {
  try {
    if (!_audioCtx) {
      const Ctx = window.AudioContext || window.webkitAudioContext;
      if (!Ctx) return;
      _audioCtx = new Ctx();
    }
    const ctx = _audioCtx;
    if (ctx.state === "suspended") ctx.resume();

    const now = ctx.currentTime;
    const duration = 0.85;

    // Three slightly detuned square-wave oscillators give the "blat" of a real air horn
    const freqs = [220, 277, 330];
    const master = ctx.createGain();
    master.gain.setValueAtTime(0, now);
    master.gain.linearRampToValueAtTime(0.18, now + 0.04);
    master.gain.setValueAtTime(0.18, now + duration - 0.18);
    master.gain.exponentialRampToValueAtTime(0.001, now + duration);
    master.connect(ctx.destination);

    // Slight low-pass to take harsh edges off the squarewave
    const filter = ctx.createBiquadFilter();
    filter.type = "lowpass";
    filter.frequency.value = 1800;
    filter.Q.value = 1.2;
    filter.connect(master);

    freqs.forEach((f, i) => {
      const osc = ctx.createOscillator();
      osc.type = "square";
      osc.frequency.setValueAtTime(f, now);
      // Tiny pitch wobble for realism
      osc.frequency.linearRampToValueAtTime(f * 1.02, now + 0.15);
      osc.frequency.linearRampToValueAtTime(f * 0.98, now + duration - 0.1);
      const oscGain = ctx.createGain();
      oscGain.gain.value = i === 0 ? 0.6 : 0.4;
      osc.connect(oscGain);
      oscGain.connect(filter);
      osc.start(now);
      osc.stop(now + duration + 0.05);
    });
  } catch (e) {
    console.warn("honk failed", e);
  }
}
window.honkAirHorn = honkAirHorn;

function HomePage({ onNav, onCity }) {
  const [query, setQuery] = useStateH("");
  const [focused, setFocused] = useStateH(false);
  const [hoveredCity, setHoveredCity] = useStateH(null);
  const [activeCategory, setActiveCategory] = useStateH("small");

  const { ALL_CITIES, FEATURED_CITIES, SHIPPING_CATEGORIES, INSIGHTS } = window.SI_DATA;

  const matches = useMemoH(() => {
    if (!query.trim()) return [];
    const q = query.toLowerCase();
    return ALL_CITIES.filter(c => c.name.toLowerCase().includes(q) || c.state.toLowerCase().includes(q)).slice(0, 6);
  }, [query]);

  return (
    <div className="page-home">
      {/* HERO */}
      <section className="hero hero-with-trucks">
        {/* Animated trucks rolling across the bottom — click for air horn */}
        <div className="hero-trucks" aria-hidden="false">
          <div className="hero-road" />
          <button
            type="button"
            className="hero-truck truck-1"
            onClick={honkAirHorn}
            aria-label="Honk! (click any truck)"
            title="Honk!"
          >
            <svg viewBox="0 0 200 70" width="200" height="70" fill="none">
              <rect x="2" y="6" width="128" height="42" rx="2" stroke="currentColor" strokeWidth="2.5" fill="var(--paper)"/>
              <line x1="22" y1="6" x2="22" y2="48" stroke="currentColor" strokeWidth="1.2" opacity="0.5"/>
              <line x1="64" y1="6" x2="64" y2="48" stroke="currentColor" strokeWidth="1.2" opacity="0.5"/>
              <line x1="106" y1="6" x2="106" y2="48" stroke="currentColor" strokeWidth="1.2" opacity="0.5"/>
              <path d="M132 48 L132 22 L154 22 L168 32 L168 48 Z" stroke="currentColor" strokeWidth="2.5" fill="var(--paper)"/>
              <rect x="154" y="24" width="11" height="9" stroke="currentColor" strokeWidth="1.5" fill="var(--paper)"/>
              <circle cx="146" cy="20" r="2" fill="currentColor"/>
              <circle cx="22" cy="55" r="8" stroke="currentColor" strokeWidth="2.5" fill="var(--paper)"/>
              <circle cx="40" cy="55" r="8" stroke="currentColor" strokeWidth="2.5" fill="var(--paper)"/>
              <circle cx="108" cy="55" r="8" stroke="currentColor" strokeWidth="2.5" fill="var(--paper)"/>
              <circle cx="148" cy="55" r="8" stroke="currentColor" strokeWidth="2.5" fill="var(--paper)"/>
            </svg>
          </button>
          <button
            type="button"
            className="hero-truck truck-2"
            onClick={honkAirHorn}
            aria-label="Honk!"
            title="Honk!"
          >
            <svg viewBox="0 0 200 70" width="200" height="70" fill="none">
              <rect x="2" y="6" width="128" height="42" rx="2" stroke="currentColor" strokeWidth="2.5" fill="var(--paper)"/>
              <path d="M132 48 L132 22 L154 22 L168 32 L168 48 Z" stroke="currentColor" strokeWidth="2.5" fill="var(--paper)"/>
              <rect x="154" y="24" width="11" height="9" stroke="currentColor" strokeWidth="1.5" fill="var(--paper)"/>
              <circle cx="22" cy="55" r="8" stroke="currentColor" strokeWidth="2.5" fill="var(--paper)"/>
              <circle cx="40" cy="55" r="8" stroke="currentColor" strokeWidth="2.5" fill="var(--paper)"/>
              <circle cx="108" cy="55" r="8" stroke="currentColor" strokeWidth="2.5" fill="var(--paper)"/>
              <circle cx="148" cy="55" r="8" stroke="currentColor" strokeWidth="2.5" fill="var(--paper)"/>
            </svg>
          </button>
          <button
            type="button"
            className="hero-truck truck-3"
            onClick={honkAirHorn}
            aria-label="Honk!"
            title="Honk!"
          >
            <svg viewBox="0 0 200 70" width="200" height="70" fill="none">
              <rect x="2" y="6" width="128" height="42" rx="2" stroke="currentColor" strokeWidth="2.5" fill="var(--paper)"/>
              <line x1="32" y1="6" x2="32" y2="48" stroke="currentColor" strokeWidth="1.2" opacity="0.5"/>
              <line x1="80" y1="6" x2="80" y2="48" stroke="currentColor" strokeWidth="1.2" opacity="0.5"/>
              <path d="M132 48 L132 22 L154 22 L168 32 L168 48 Z" stroke="currentColor" strokeWidth="2.5" fill="var(--paper)"/>
              <rect x="154" y="24" width="11" height="9" stroke="currentColor" strokeWidth="1.5" fill="var(--paper)"/>
              <circle cx="22" cy="55" r="8" stroke="currentColor" strokeWidth="2.5" fill="var(--paper)"/>
              <circle cx="40" cy="55" r="8" stroke="currentColor" strokeWidth="2.5" fill="var(--paper)"/>
              <circle cx="108" cy="55" r="8" stroke="currentColor" strokeWidth="2.5" fill="var(--paper)"/>
              <circle cx="148" cy="55" r="8" stroke="currentColor" strokeWidth="2.5" fill="var(--paper)"/>
            </svg>
          </button>
        </div>
        <div className="hero-inner">
          <div className="hero-eyebrow">
            <span className="eyebrow-dot" />
            Independent freight intelligence · 5 metros · Q3 2026 launch
          </div>
          <h1 className="hero-title">
            Is your package going to make it?<br/>
            <em>Did you check the pulse?</em>
          </h1>
          <p className="hero-sub">
            Shipping Clarity Pulse is the daily intelligence shippers use before freight
            starts moving. Terminal status, lane conditions, capacity, carrier ratings &mdash;
            for your metro, every morning.
          </p>

          {/* Search */}
          <div className="hero-search-wrap">
            <div className={`hero-search ${focused ? "focused" : ""}`}>
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" style={{ flexShrink: 0, color: "var(--ink-soft)" }}>
                <circle cx="11" cy="11" r="7" /><path d="m20 20-3.5-3.5" />
              </svg>
              <input
                type="text"
                placeholder="Enter a city, metro, or ZIP…"
                value={query}
                onChange={(e) => setQuery(e.target.value)}
                onFocus={() => setFocused(true)}
                onBlur={() => setTimeout(() => setFocused(false), 180)}
                className="hero-search-input"
              />
              <button
                className="hero-search-btn"
                onClick={() => { if (matches[0]) onCity(matches[0].id); else onCity("los-angeles"); }}
              >See report →</button>
            </div>
            {focused && matches.length > 0 && (
              <div className="search-dropdown">
                {matches.map(m => (
                  <button key={m.id} className="search-result" onMouseDown={() => onCity(m.id)}>
                    <span className="search-result-name">{m.name}, <span style={{ color: "var(--ink-soft)" }}>{m.state}</span></span>
                    <span className="search-result-meta">{m.pop}</span>
                  </button>
                ))}
              </div>
            )}
            {focused && query.trim() && matches.length === 0 && (
              <div className="search-dropdown">
                <div style={{ padding: "16px", color: "var(--ink-soft)", fontSize: 14 }}>
                  No metros match "{query}" yet — we're adding new cities every month.
                </div>
              </div>
            )}
          </div>

          <div className="hero-quick">
            <span className="hero-quick-label">Popular:</span>
            {["los-angeles", "new-york", "chicago", "dallas", "atlanta"].map(id => {
              const c = FEATURED_CITIES.find(f => f.id === id);
              return (
                <button key={id} className="hero-quick-chip" onClick={() => onCity(id)}>
                  {c.name}
                </button>
              );
            })}
          </div>
        </div>

        {/* Stat strip */}
        <div className="hero-stats">
          <div className="hero-stat">
            <div className="hero-stat-num">47</div>
            <div className="hero-stat-label">Metros graded</div>
          </div>
          <div className="hero-stat">
            <div className="hero-stat-num">128</div>
            <div className="hero-stat-label">Carriers tracked</div>
          </div>
          <div className="hero-stat">
            <div className="hero-stat-num">14M</div>
            <div className="hero-stat-label">Shipments analyzed</div>
          </div>
          <div className="hero-stat">
            <div className="hero-stat-num">5</div>
            <div className="hero-stat-label">Shipping categories</div>
          </div>
        </div>
      </section>

      {/* PULSE — daily intelligence subscription signup */}
      <PulseSignupSection />

      {/* CATEGORIES STRIP */}
      <section className="cat-strip">
        <div className="cat-strip-inner">
          <div className="section-eyebrow">From a postcard to a 53-foot trailer.</div>
          <h2 className="section-title">Five categories. One report card.</h2>
          <div className="cat-grid">
            {SHIPPING_CATEGORIES.map((c, i) => (
              <button
                key={c.id}
                className={`cat-card ${activeCategory === c.id ? "active" : ""}`}
                onClick={() => setActiveCategory(c.id)}
              >
                <div className="cat-num">0{i + 1}</div>
                <div className="cat-label">{c.label}</div>
                <div className="cat-desc">{c.desc}</div>
                <div className="cat-arrow">→</div>
              </button>
            ))}
          </div>
        </div>
      </section>

      {/* MAP + FEATURED */}
      <section className="map-section">
        <div className="map-section-inner">
          <div className="map-header">
            <div>
              <div className="section-eyebrow">Coverage</div>
              <h2 className="section-title">Metros we grade.</h2>
            </div>
            <div className="map-legend">
              <span className="legend-item"><span className="legend-dot" style={{ background: "var(--green)" }}/>A</span>
              <span className="legend-item"><span className="legend-dot" style={{ background: "var(--ink)" }}/>B</span>
              <span className="legend-item"><span className="legend-dot" style={{ background: "var(--amber)" }}/>C</span>
              <span className="legend-item"><span className="legend-dot" style={{ background: "var(--red)" }}/>D/F</span>
            </div>
          </div>

          <div className="city-grid">
            {FEATURED_CITIES.map((c) => (
              <button
                key={c.id}
                className="city-tile"
                onClick={() => onCity(c.id)}
              >
                <div className="city-tile-top">
                  <div className="city-tile-name">{c.name}</div>
                  <div className="city-tile-state">{c.state}</div>
                </div>
                <div className="city-tile-mid">
                  {c.topCarrier && (
                    <div className="city-tile-leader">
                      <span className="city-tile-leader-l">Top</span>{" "}
                      {c.topCarrier}
                    </div>
                  )}
                  {c.pop && <div className="city-tile-pop">{c.pop} metro pop.</div>}
                </div>
                <div className="city-tile-bottom">
                  <LetterBadge score={letterToScore(c.topGrade)} size="md" />
                  <span className="city-tile-arrow">→</span>
                </div>
              </button>
            ))}
          </div>
        </div>
      </section>

      {/* HOW IT WORKS */}
      <section className="how-section">
        <div className="how-inner">
          <div className="section-eyebrow">Methodology</div>
          <h2 className="section-title">How the grading works.</h2>
          <div className="how-grid">
            <div className="how-card">
              <div className="how-num">01</div>
              <div className="how-h">Real shipment data</div>
              <p className="how-p">We aggregate tracking, transit, and delivery outcomes from our shipper network — 14M+ shipments across 47 metros each quarter.</p>
            </div>
            <div className="how-card">
              <div className="how-num">02</div>
              <div className="how-h">8 weighted metrics</div>
              <p className="how-p">On-time, damage rate, customer service, tracking accuracy, transit vs. promise, pricing, pickup, and driver professionalism.</p>
            </div>
            <div className="how-card">
              <div className="how-num">03</div>
              <div className="how-h">A 0–100 score, A+ to F</div>
              <p className="how-p">Every carrier in every category gets a Clarity Score and a letter grade. No pay-to-rank — sponsored placements are clearly marked.</p>
            </div>
            <div className="how-card">
              <div className="how-num">04</div>
              <div className="how-h">Updated quarterly</div>
              <p className="how-p">Reports refresh every 90 days so the rankings reflect what's happening on the road right now, not a year ago.</p>
            </div>
          </div>
        </div>
      </section>

      {/* INSIGHTS */}
      <section className="insights-section">
        <div className="insights-inner">
          <div className="insights-head">
            <div>
              <div className="section-eyebrow">From the desk</div>
              <h2 className="section-title">Latest from Clarity.</h2>
            </div>
            <button className="btn-ghost" onClick={() => onNav("insights")}>All articles →</button>
          </div>
          <div className="insights-grid">
            {INSIGHTS.map((i, idx) => (
              <article key={idx} className="insight-card" onClick={() => onNav("insights")}>
                <div className="insight-tag">{i.tag}</div>
                <h3 className="insight-title">{i.title}</h3>
                <div className="insight-meta">
                  <span>{i.date}</span><span className="dot-sep">·</span><span>{i.read} read</span>
                </div>
              </article>
            ))}
          </div>
        </div>
      </section>

      {/* CTA */}
      <section className="cta-section">
        <div className="cta-inner">
          <h2 className="cta-title">Are you a carrier?</h2>
          <p className="cta-p">Claim your profile, respond to your grades, and reach shippers actively looking for someone who delivers.</p>
          <div className="cta-actions">
            <button className="btn-primary-lg" onClick={() => onNav("members")}>List your company</button>
            <button className="btn-ghost-lg" onClick={() => onNav("members")}>See advertising →</button>
          </div>
        </div>
      </section>
    </div>
  );
}

// Helper: rough letter→score for the rank-sorting
function letterToScore(l) {
  const map = { "A+": 95, "A": 90, "A-": 85, "B+": 80, "B": 75, "B-": 70, "C+": 65, "C": 60, "C-": 55, "D+": 50, "D": 45, "D-": 40, "F": 30 };
  return map[l] || 70;
}
function letterRank(l) { return letterToScore(l); }

// =============================================================
// US MAP — stylized dot map
// =============================================================
function USMap({ cities, hovered, setHovered, onCity }) {
  return (
    <div className="us-map">
      <svg viewBox="0 0 100 70" className="us-map-svg" preserveAspectRatio="xMidYMid meet">
        {/* Stylized US outline — abstract shape */}
        <path d="M 8 20 Q 10 14 14 12 L 22 10 L 35 9 L 50 8 L 68 9 L 82 11 L 90 14 Q 94 18 92 24 L 90 32 Q 88 40 84 46 L 80 56 Q 76 64 70 66 L 60 67 L 48 68 L 36 67 L 24 64 L 16 58 Q 10 52 8 44 L 6 32 Q 6 24 8 20 Z"
          fill="var(--paper-2)" stroke="var(--rule-soft)" strokeWidth="0.3" />
        {/* Florida nub */}
        <path d="M 78 60 Q 82 64 84 70 L 80 68 L 78 64 Z" fill="var(--paper-2)" stroke="var(--rule-soft)" strokeWidth="0.3" />
        {/* Texas-ish */}
        <path d="M 44 60 L 56 62 L 56 70 L 48 70 L 44 66 Z" fill="var(--paper-2)" stroke="var(--rule-soft)" strokeWidth="0.3" />

        {/* Soft grid */}
        {[...Array(7)].map((_, i) => (
          <line key={`h${i}`} x1="0" y1={i*10} x2="100" y2={i*10} stroke="var(--rule-soft)" strokeWidth="0.1" opacity="0.5" />
        ))}
        {[...Array(11)].map((_, i) => (
          <line key={`v${i}`} x1={i*10} y1="0" x2={i*10} y2="70" stroke="var(--rule-soft)" strokeWidth="0.1" opacity="0.5" />
        ))}

        {/* City pins */}
        {cities.map(c => {
          const score = letterToScore(c.topGrade);
          let fill = "var(--ink)";
          if (score >= 85) fill = "var(--green)";
          else if (score >= 70) fill = "var(--ink)";
          else if (score >= 55) fill = "var(--amber)";
          else fill = "var(--red)";
          const isHovered = hovered?.id === c.id;
          return (
            <g key={c.id}
              style={{ cursor: "pointer" }}
              onMouseEnter={() => setHovered(c)}
              onMouseLeave={() => setHovered(null)}
              onClick={() => onCity(c.id)}
            >
              <circle cx={c.x} cy={c.y} r={isHovered ? 3.4 : 1.6} fill={fill} opacity="0.18"
                style={{ transition: "r 200ms" }} />
              <circle cx={c.x} cy={c.y} r={isHovered ? 1.6 : 1.0} fill={fill}
                style={{ transition: "r 200ms" }} />
              {isHovered && (
                <text x={c.x} y={c.y - 2.5} textAnchor="middle"
                  fontFamily="var(--font-mono)" fontSize="2.2" fill="var(--ink)" fontWeight="500">
                  {c.name} · {c.topGrade}
                </text>
              )}
            </g>
          );
        })}
      </svg>
    </div>
  );
}

function CityHoverCard({ city, onCity }) {
  return (
    <div className="city-hover-card">
      <div className="city-hover-name">{city.name}</div>
      <div className="city-hover-state">{city.state} · {city.pop}</div>
      <div className="city-hover-grade-row">
        <div>
          <div className="city-hover-label">Top carrier</div>
          <div className="city-hover-val">{city.topCarrier}</div>
        </div>
        <LetterBadge score={letterToScore(city.topGrade)} size="lg" />
      </div>
      <button className="city-hover-cta" onClick={() => onCity(city.id)}>
        See full report →
      </button>
    </div>
  );
}

window.HomePage = HomePage;

// =============================================================================
// PULSE SIGNUP — daily intelligence subscription waitlist
// =============================================================================
function PulseSignupSection() {
  const [email, setEmail] = useStateH("");
  const [city, setCity] = useStateH("denver");
  const [submitted, setSubmitted] = useStateH(false);
  const cities = (window.SI_DATA && window.SI_DATA.FEATURED_CITIES) || [
    { id: "denver", name: "Denver" },
    { id: "los-angeles", name: "Los Angeles" },
    { id: "new-york", name: "New York" },
    { id: "chicago", name: "Chicago" },
    { id: "atlanta", name: "Atlanta" },
  ];
  const cityName = (cities.find((c) => c.id === city) || cities[0]).name;

  async function submit(e) {
    e.preventDefault();
    if (!email.trim() || !email.includes("@")) return;
    if (window.SI_DB && window.SI_DB.submitNewsletterSignup) {
      try {
        await window.SI_DB.submitNewsletterSignup(email.trim(), `pulse_${city}`);
      } catch (err) { console.warn("pulse signup err", err); }
    }
    setSubmitted(true);
  }

  return (
    <section className="pulse-section">
      <div className="pulse-inner">
        <div className="pulse-grid">
          <div className="pulse-pitch">
            <div className="section-eyebrow">Shipping Clarity Pulse</div>
            <h2 className="section-title">
              Daily intelligence for your <em>shipping reality.</em>
            </h2>
            <p className="pulse-sub">
              Every morning at 7am, get the pulse for your metro: which terminals
              are running hot, where wait times are spiking, which lanes are degraded,
              and what's expected this week. The intelligence shippers need before
              freight starts moving.
            </p>
            <ul className="pulse-bullets">
              <li>Terminal status changes and live wait times</li>
              <li>Lane conditions and corridor health</li>
              <li>Capacity shifts and carrier ratings updates</li>
              <li>Weekly trend reports per metro</li>
            </ul>
          </div>

          <div className="pulse-card">
            <div className="pulse-card-tag">Q3 2026 Launch · Get notified</div>
            {submitted ? (
              <div className="pulse-card-thanks">
                <div className="pulse-card-thanks-h">✓ You're on the list.</div>
                <p>We'll let you know when the {cityName} Pulse goes live.</p>
              </div>
            ) : (
              <form className="pulse-form" onSubmit={submit}>
                <label className="pulse-label">Your metro</label>
                <select
                  className="pulse-select"
                  value={city}
                  onChange={(e) => setCity(e.target.value)}
                >
                  {cities.map((c) => (
                    <option key={c.id} value={c.id}>{c.name}</option>
                  ))}
                </select>
                <label className="pulse-label">Work email</label>
                <input
                  type="email"
                  required
                  className="pulse-email"
                  placeholder="you@company.com"
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                />
                <button type="submit" className="btn-primary pulse-submit">
                  Get the {cityName} Pulse →
                </button>
                <p className="pulse-fineprint">
                  Free preview. We'll never share your address.
                </p>
              </form>
            )}
          </div>
        </div>
      </div>
    </section>
  );
}

// =============================================================================
// PERSPECTIVES — kept defined but unused on homepage. Will reuse on internal
// audience-specific pages once the four Reports launch.
// =============================================================================
function PerspectivesSection() {
  const PERSPECTIVES = [
    {
      key: "shippers",
      tone: "blue",
      audience: "Shippers don't see",
      body: (<>
        <p>
          Did you know that when you ship UPS air freight out of Denver, your package
          isn't moved by one truck? It's relayed between drivers — Commerce City to
          Englewood — to make the plane that night. <em>Hope they relayed them all.</em>
        </p>
        <p>
          Right now Commerce City is closed for remodel. Trucks are routing through
          Littleton. Every relay just got longer. Your package's odds of making the
          plane just got shorter.
        </p>
      </>),
      pitch: <><strong>Shippers Report</strong> shows you the chain you're paying for, not just the carrier name on the invoice.</>,
    },
    {
      key: "receivers",
      tone: "green",
      audience: "Receivers don't see",
      body: (<>
        <p>
          Did you know the freight that just hit your dock came off a relay from a driver
          who waited 4 hours at a shipper, then ran tired? Or that one of your regular
          inbound carriers is known on BrownCafe as <em>"the one that pays for damage
          and never pays the claim"</em>?
        </p>
        <p>
          Receivers judge carriers by what arrives. We show you the trip that got it
          there — and what the next one will look like.
        </p>
      </>),
      pitch: <><strong>Receivers Report</strong> turns inbound freight from a black box into a forecast.</>,
    },
    {
      key: "carriers",
      tone: "amber",
      audience: "Carriers don't see",
      body: (<>
        <p>
          Did you know your drivers are talking about you right now on BrownCafe,
          TruckersReport, and Reddit? Did you know there's a permit pending on your top
          competitor's main hub that'll take them offline next quarter?
        </p>
        <p>
          You don't have to wait for the RFP loss to find out. Other people see your
          business clearer than you do.
        </p>
      </>),
      pitch: <><strong>Carriers Report</strong> is your ground truth — including the parts about you.</>,
    },
    {
      key: "brokers",
      tone: "red",
      audience: "Brokers don't see",
      body: (<>
        <p>
          Did you know the carrier you just booked for that 53-foot lane lost their
          authority three weeks ago and is running under another MC? Did you know the
          driver assigned to your hot load just logged two HOS violations?
        </p>
        <p>
          Trust pays well — until it doesn't. <em>Verify everything.</em>
        </p>
      </>),
      pitch: <><strong>Broker Report</strong> is real-time carrier qualification — authority, insurance, safety, lane reputation.</>,
    },
  ];

  return (
    <section className="perspectives-section">
      <div className="perspectives-inner">
        <div className="section-eyebrow">What you don't see</div>
        <h2 className="section-title">Four perspectives. <em>One picture.</em></h2>
        <p className="perspectives-sub">
          Every player in the supply chain sees a different slice of the truth.
          Shipping Clarity is the first time everyone sees the whole thing.
        </p>

        <div className="perspectives-grid">
          {PERSPECTIVES.map((p) => (
            <PerspectiveCard key={p.key} {...p} />
          ))}
        </div>
      </div>
    </section>
  );
}

function PerspectiveCard({ key: k, tone, audience, body, pitch }) {
  const [email, setEmail] = useStateH("");
  const [submitted, setSubmitted] = useStateH(false);
  const [open, setOpen] = useStateH(false);
  const audienceKey = audience.split(" ")[0].toLowerCase(); // "shippers" / "receivers" / etc.

  async function submit(e) {
    e.preventDefault();
    if (!email.trim() || !email.includes("@")) return;
    if (window.SI_DB && window.SI_DB.submitNewsletterSignup) {
      try {
        await window.SI_DB.submitNewsletterSignup(email.trim(), `report_${audienceKey}`);
      } catch (err) { console.warn("signup err", err); }
    }
    setSubmitted(true);
  }

  return (
    <div className={`p-card p-card-${tone}`}>
      <div className="p-card-tag">{audience}</div>
      <div className="p-card-body">{body}</div>
      <div className="p-card-pitch">{pitch}</div>
      <div className="p-card-cta">
        {!open && !submitted && (
          <button className="p-card-btn" onClick={() => setOpen(true)}>
            Notify me when it's live →
          </button>
        )}
        {open && !submitted && (
          <form className="p-card-form" onSubmit={submit}>
            <input
              type="email"
              required
              placeholder="you@company.com"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              autoFocus
            />
            <button type="submit" className="btn-primary">Notify me</button>
          </form>
        )}
        {submitted && (
          <div className="p-card-thanks">✓ You're on the list. We'll write when it launches.</div>
        )}
        <div className="p-card-meta">Coming Q3 2026 · Powered by Shipping Clarity</div>
      </div>
    </div>
  );
}
