// Map + Leaderboard + Traders sections

function MapSection({ heatmap = false, heatmapIntensity = 0.7 }) {
  const [active, setActive] = React.useState(null);
  const [filters, setFilters] = React.useState({ rig: true, mil: true, teleport: true, event: true, bm: true });
  const [points, setPoints] = React.useState([]);
  const [meta, setMeta] = React.useState({ source: "demo", delayMinutes: 60 });
  const [pins] = usePins();
  const mapImage = useMapImage();

  // Public site only ever sees public pins, never admin-only ones (hidden trader).
  const publicPins = pins.filter(p => p.public !== false);
  const counts = publicPins.reduce((a, m) => ({...a, [m.type]: (a[m.type]||0)+1}), {});
  const toggle = k => setFilters(f => ({ ...f, [k]: !f[k] }));

  React.useEffect(() => {
    let stopped = false;
    (async () => {
      const real = await ShovelheadLive.fetchHeatmapPoints();
      if (stopped) return;
      if (real) {
        setPoints(real.points);
        setMeta({ source: "live", delayMinutes: real.delayMinutes, generatedAt: real.generatedAt });
      } else {
        const demo = ShovelheadLive.demoHeatmapPoints();
        setPoints(demo.points);
        setMeta({ source: "demo", delayMinutes: demo.delayMinutes });
      }
    })();
    return () => { stopped = true; };
  }, []);

  return (
    <section id="map">
      <div className="shell">
        <SectionHead
          num="§04 — MAP"
          title={<>CHERNARUS<br/>HOTSPOTS.</>}
          sub={<>Military tier loot zones and offshore rigs across Chernarus. Click any pin for details.</>}
        />

        <div className="map-wrap">
          <div className="map-stage" style={mapImage ? {
            backgroundImage: `url(${mapImage})`,
            backgroundSize: "cover",
            backgroundPosition: "center",
          } : undefined}>
            {!mapImage && (
              <svg className="map-svg" viewBox="0 0 100 100" preserveAspectRatio="none">
                <defs>
                  <pattern id="hatch" width="3" height="3" patternUnits="userSpaceOnUse" patternTransform="rotate(45)">
                    <line x1="0" y1="0" x2="0" y2="3" stroke="var(--line)" strokeWidth="0.4"/>
                  </pattern>
                </defs>
                <rect width="100" height="100" fill="var(--bg-3)"/>
                <path d="M3 8 Q12 4 28 6 Q45 3 60 5 Q78 4 92 10 Q97 22 95 38 Q97 55 92 68 Q88 80 78 86 Q60 91 42 88 Q22 91 10 82 Q3 70 5 50 Q2 28 3 8 Z"
                      fill="var(--bg-2)" stroke="var(--line-2)" strokeWidth="0.3"/>
                <path d="M3 8 Q12 4 28 6 Q45 3 60 5 Q78 4 92 10 Q97 22 95 38 Q97 55 92 68 Q88 80 78 86 Q60 91 42 88 Q22 91 10 82 Q3 70 5 50 Q2 28 3 8 Z"
                      fill="url(#hatch)" opacity="0.5"/>
                <path d="M3 88 Q22 92 42 88 Q60 91 78 86 Q88 80 92 75" fill="none" stroke="var(--accent-2)" strokeWidth="0.3" opacity="0.4"/>
                <path d="M45 12 Q42 30 50 48 Q55 65 52 86" fill="none" stroke="var(--accent-2)" strokeWidth="0.4" opacity="0.35"/>
                <path d="M70 18 Q66 32 70 50" fill="none" stroke="var(--accent-2)" strokeWidth="0.3" opacity="0.3"/>
                {Array.from({length: 9}).map((_, i) => (
                  <line key={"x"+i} x1={(i+1)*10} x2={(i+1)*10} y1="0" y2="100" stroke="var(--line)" strokeWidth="0.2" strokeDasharray="0.5 1.5"/>
                ))}
                {Array.from({length: 9}).map((_, i) => (
                  <line key={"y"+i} x1="0" x2="100" y1={(i+1)*10} y2={(i+1)*10} stroke="var(--line)" strokeWidth="0.2" strokeDasharray="0.5 1.5"/>
                ))}
                {["A","B","C","D","E","F","G","H","I","J"].map((c, i) => (
                  <text key={c} x={i*10 + 5} y="3.5" fill="var(--ink-4)" fontSize="2" fontFamily="JetBrains Mono">{c}</text>
                ))}
              </svg>
            )}

            {heatmap && points.length > 0 && (
              <MapHeatmap points={points} intensity={heatmapIntensity} blur={26} />
            )}

            {publicPins.filter(m => filters[m.type]).map(m => (
              <div
                key={m.id}
                className={`map-marker ${m.type}`}
                style={{ left: m.x * 100 + "%", top: m.y * 100 + "%" }}
                onMouseEnter={() => setActive(m)}
                onMouseLeave={() => setActive(null)}
              >
                {m.type === "rig"   && "▲"}
                {m.type === "mil"   && "M"}
                {m.type === "event" && "✦"}
                {m.type === "bm"    && "$"}
              </div>
            ))}

            {active && (
              <div className="map-tooltip" style={{ left: active.x * 100 + "%", top: active.y * 100 + "%" }}>
                <div className="ttt">{active.label}</div>
                <div className="ttd">{active.desc}</div>
                <div className="ttd" style={{marginTop:4,fontFamily:"JetBrains Mono",fontSize:10,letterSpacing:"0.12em",color:"var(--ink-3)"}}>
                  GRID {DAYZ.normToGrid(active.x, active.y)}
                </div>
              </div>
            )}

            <div style={{position:"absolute",bottom:12,left:12,fontFamily:"JetBrains Mono",fontSize:10,letterSpacing:"0.14em",color:"var(--ink-4)"}}>
              CHERNARUS — 225 km² · SEASON 01
            </div>
            <div style={{position:"absolute",bottom:12,right:12,fontFamily:"JetBrains Mono",fontSize:10,letterSpacing:"0.14em",color:"var(--ink-4)"}}>
              {mapImage ? "CUSTOM MAP IMAGE" : "SCALE 1:100K"}
            </div>
          </div>

          <aside className="map-legend">
            <div className="lh">— LAYERS</div>
            {[
              { t: "rig",   l: "Oil rigs" },
              { t: "mil",   l: "Military loot" },
              { t: "teleport", l: "Trader teleports" },
              { t: "bm",    l: "Black market" },
              { t: "event", l: "Dynamic events" },
            ].map(row => (
              <div key={row.t} className={"legend-row" + (filters[row.t] ? "" : " off")} data-t={row.t} onClick={() => toggle(row.t)}>
                <div className="l"><div className="dot-l"></div>{row.l}</div>
                <div className="c">{counts[row.t] || 0}</div>
              </div>
            ))}

            {heatmap && (
              <div style={{marginTop:16, padding:"12px", border:"1px dashed var(--accent)", background:"color-mix(in oklab, var(--accent) 8%, transparent)"}}>
                <div className="lh" style={{marginBottom:8}}>— DEATH HEATMAP</div>
                <div style={{display:"flex",alignItems:"center",gap:8,fontSize:11,fontFamily:"JetBrains Mono",letterSpacing:"0.1em",color:"var(--ink-2)"}}>
                  <div style={{width:80,height:8,background:"linear-gradient(to right,#2a6fdb,#7eb4d4,#e6c454,#d94a2b)"}}></div>
                  <span>FEW → KILL ZONE</span>
                </div>
                <div style={{marginTop:10, fontFamily:"JetBrains Mono",fontSize:10,letterSpacing:"0.12em",color:"var(--ink-3)"}}>
                  DEATHS · <span style={{color:"var(--ink)"}}>{points.length}</span><br/>
                  WINDOW · <span style={{color:"var(--ink)"}}>7 DAYS</span><br/>
                  SRC · <span style={{color: meta.source === "live" ? "var(--good)" : "var(--ink-3)"}}>{meta.source === "live" ? "LIVE FEED" : "DEMO POINTS"}</span>
                </div>
              </div>
            )}

            <div className="map-coords">
              SEASON · <span className="v">01</span><br/>
              WIPE · <span className="v">{SERVER.wipe}</span><br/>
              EVENTS · <span className="v">HOURLY</span>
            </div>
          </aside>
        </div>
      </div>
    </section>
  );
}

function LeaderboardSection() {
  const [sort, setSort] = React.useState("kills");
  const live = useLeaderboard();
  const rawRows = live.rows && live.rows.length ? live.rows : LEADERBOARD;
  const sorted = [...rawRows].sort((a,b) => (b[sort] ?? 0) - (a[sort] ?? 0))
                              .map((p, i) => ({...p, rank: i+1}));

  return (
    <section id="leaderboard">
      <div className="shell">
        <SectionHead
          num="§05 — LEADERBOARD"
          title={<>SEASON 01<br/>SCOREBOARD.</>}
          sub={<>Stats reset on wipe. Top 12 by kill count over the last 7 days. Longest shot recorded from the in-game kill-feed.</>}
        />

        <div className="lb-toolbar">
          <div className="mono" style={{fontSize:11,color:"var(--ink-3)",letterSpacing:"0.14em",textTransform:"uppercase"}}>
            SORT BY
          </div>
          <div className="lb-sort">
            {[
              { k: "kills",   l: "Kills" },
              { k: "kd",      l: "K/D" },
              { k: "hours",   l: "Hours" },
              { k: "longest", l: "Longest shot" },
            ].map(s => (
              <button key={s.k} className={"chip" + (sort === s.k ? " on" : "")} onClick={() => setSort(s.k)}>{s.l}</button>
            ))}
          </div>
        </div>

        <div className="lb-table">
          <div className="lb-row head">
            <div>RANK</div>
            <div>SURVIVOR</div>
            <div style={{textAlign:"right"}}>KILLS</div>
            <div style={{textAlign:"right"}}>DEATHS</div>
            <div style={{textAlign:"right"}}>K/D</div>
            <div style={{textAlign:"right"}}>HOURS</div>
            <div style={{textAlign:"right"}}>LONGEST</div>
          </div>
          {sorted.map(p => (
            <div className="lb-row" key={p.name}>
              <div className="lb-rank">{String(p.rank).padStart(2,"0")}</div>
              <div className="lb-name">{p.name}</div>
              <div className={"lb-num" + (sort === "kills" ? " hl" : "")}>{p.kills ?? 0}</div>
              <div className="lb-num">{p.deaths ?? 0}</div>
              <div className={"lb-num" + (sort === "kd" ? " hl" : "")}>{(p.kd ?? 0).toFixed(2)}</div>
              <div className={"lb-num" + (sort === "hours" ? " hl" : "")}>{p.hours ?? 0}h</div>
              <div className={"lb-num" + (sort === "longest" ? " hl" : "")}>{p.longest ?? 0}m</div>
            </div>
          ))}
        </div>
        <div style={{marginTop:12, fontFamily:"JetBrains Mono", fontSize:10, color:"var(--ink-4)", letterSpacing:"0.14em", textTransform:"uppercase"}}>
          {live.source === "live"
            ? <>SRC · RPT SCRAPER · <span style={{color:"var(--good)"}}>LIVE</span>{live.generatedAt ? <> · GENERATED {new Date(live.generatedAt).toLocaleString(undefined, { hour:"2-digit", minute:"2-digit", month:"short", day:"numeric" })}</> : null}</>
            : <>SRC · DEMO DATA · <span style={{color:"var(--ink-3)"}}>SET leaderboardUrl IN live-data.js</span></>}
        </div>
      </div>
    </section>
  );
}

function TradersSection() {
  const [pins] = usePins();
  const rigs = pins.filter(m => m.type === "rig");

  return (
    <section id="traders">
      <div className="shell">
        <SectionHead
          num="§06 — THE TRADER & RIGS"
          title={<>ONE TRADER.<br/>TWO OIL RIGS.</>}
          sub={<>One hidden trader — teleport-access only — handles the entire economy. Two offshore oil rigs reset every six hours with Tier-4 loot.</>}
        />

        <div className="hidden-trader">
          <div className="ht-stamp">CLASSIFIED · ADMIN-ONLY COORDS</div>
          <div className="ht-grid">
            <div className="ht-icon" aria-hidden="true">
              <svg viewBox="0 0 80 80" fill="none">
                <circle cx="40" cy="40" r="34" stroke="var(--accent)" strokeWidth="1.5" strokeDasharray="3 4"/>
                <circle cx="40" cy="40" r="22" stroke="var(--accent)" strokeWidth="1" strokeDasharray="2 3"/>
                <text x="40" y="48" textAnchor="middle" fontFamily="Anton" fontSize="32" fill="var(--accent)" letterSpacing="0.04em">?</text>
              </svg>
            </div>
            <div>
              <div className="ht-title">THE TRADER</div>
              <div className="ht-line">LOCATION · <span className="ht-redact">[REDACTED]</span></div>
              <div className="ht-line">ACCESS · <span style={{color:"var(--ink)"}}>IN-GAME TELEPORT PYLON</span></div>
              <div className="ht-line">SAFE ZONE · <span style={{color:"var(--ink)"}}>200m RADIUS</span></div>
              <div className="ht-line">CURRENCY · <span style={{color:"var(--ink)"}}>ROUBLES · CROSS-CHARACTER BANKED</span></div>
              <div className="ht-line">STOCK · <span style={{color:"var(--ink)"}}>EVERYTHING · CIVILIAN → TIER 4</span></div>
              <p className="ht-copy">
                You don't approach by land. You don't approach by air. You find a working pylon, accept the risk of the queue, and trust the coordinates not to drop you into someone's open base raid. There's one trader. They take roubles. Be polite. Don't draw inside the safe zone.
              </p>
            </div>
          </div>
        </div>

        <div className="rig-grid">
          {rigs.map((r, i) => (
            <article className="rig-card" key={r.id}>
              <div className="rig-num">{String(i+1).padStart(2,"0")}</div>
              <div className="rig-body">
                <div className="rig-name">{r.label.toUpperCase()}</div>
                <div className="rig-loc">
                  GRID {DAYZ.normToGrid(r.x, r.y)} · NORM ({r.x.toFixed(2)}, {r.y.toFixed(2)})
                </div>
                <div className="rig-desc">{r.desc}</div>
                <div className="rig-tags">
                  <span className="ttag">TIER 4 LOOT</span>
                  <span className="ttag">6H RESET</span>
                  <span className="ttag">{r.id === "rig-south" ? "BOAT/CHOPPER" : "RADIATION"}</span>
                  <span className="ttag">PVP HOT</span>
                </div>
              </div>
            </article>
          ))}
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { MapSection, LeaderboardSection, TradersSection });
