/* ============================================================
   $LAND — modals
   ============================================================ */
(function () {
  const D = window.LandData, F = D.fmt;
  const { Tile } = window.Land;
  const rarByKey = window.rarByKey;

  function Scrim({ onClose, children, w = 720 }) {
    React.useEffect(() => {
      const k = (e) => e.key === 'Escape' && onClose();
      window.addEventListener('keydown', k); return () => window.removeEventListener('keydown', k);
    }, []);
    return (
      <div className="scrim" onClick={onClose}>
        <div className="modal" style={{ width: w, maxWidth: '100%' }} onClick={(e) => e.stopPropagation()}>{children}</div>
      </div>
    );
  }
  function CloseBtn({ onClose }) {
    return <button onClick={onClose} style={{ position: 'absolute', top: 16, right: 16, width: 34, height: 34, borderRadius: 10, background: 'var(--surface3)', border: '1px solid var(--line2)', fontSize: 17, color: 'var(--ink2)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 3 }}>✕</button>;
  }
  function Stat({ label, value, sub }) {
    return (
      <div style={{ padding: '12px 14px', background: 'var(--surface3)', borderRadius: 12, border: '1px solid var(--line)' }}>
        <div className="eyebrow">{label}</div>
        <div className="tnum" style={{ fontWeight: 700, fontSize: 19, fontFamily: 'var(--font-display)', marginTop: 3 }}>{value}</div>
        {sub && <div className="faint" style={{ fontSize: 11, marginTop: 1 }}>{sub}</div>}
      </div>
    );
  }

  /* ---------- HOLDER modal — real $LAND holder (map is from BALANCE) ---------- */
  function ParcelModal({ holder, onClose }) {
    const h = holder, r = rarByKey(h.rarity);
    const sharePct = (h.share || 0) * 100; // real weight-based payout share
    // per-round income estimate = round amount × this holder's share.
    const rounds = D.rounds.slice(0, 6).map(rd => ({ round: rd.round, sol: Math.round(rd.amount * (h.share || 0) * 100) / 100 }));
    const maxR = Math.max(...rounds.map(x => x.sol), 0.01);
    const mult = (h.buildingMult || 1).toFixed(2);
    return (
      <Scrim onClose={onClose} w={760}>
        <div style={{ position: 'relative' }}>
          <CloseBtn onClose={onClose} />
          <div style={{ display: 'grid', gridTemplateColumns: '260px 1fr' }}>
            {/* left: parcel art */}
            <div style={{ background: 'linear-gradient(180deg, rgba(105,162,85,.16), rgba(68,163,207,.08))', borderRight: '1px solid var(--line)', padding: '26px 18px', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 14 }}>
              <div style={{ width: 200, height: 200, border: '2.5px solid var(--black)', boxShadow: 'var(--shadow)', background: 'var(--surface3)' }}><Tile kind="parcel" rarity={h.rarity} size={195} seed={h.id * 13 + 5} /></div>
              <window.RarityBadge rk={h.rarity} />
              <div className="mono faint" style={{ fontSize: 11, textAlign: 'center' }}>{h.cells.length} tiles · {r.label}</div>
            </div>
            {/* right: details */}
            <div style={{ padding: '24px 26px' }}>
              <div className="eyebrow">Land holder · rank #{h.rank}</div>
              <h2 style={{ fontSize: 22, marginTop: 6, fontFamily: 'var(--font-mono)' }} className="mono">{F.addr(h.address, 6)}</h2>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 6 }}>
                <window.Addr a={h.address} n={7} />
                <window.ExtLink label="Solscan" href={'https://solscan.io/account/' + h.address} />
              </div>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, marginTop: 18 }}>
                <Stat label="$LAND held" value={F.land(h.vol)} sub={'rank #' + h.rank + ' of ' + D.holders.length} />
                <Stat label="Payout share" value={sharePct.toFixed(2) + '%'} sub={'area × ' + mult + ' building mult'} />
              </div>

              <div className="eyebrow" style={{ marginTop: 22 }}>Buildings held</div>
              <div className="faint" style={{ fontSize: 13, marginTop: 8 }}>
                {h.buildingsCount > 0
                  ? <span><b style={{ color: 'var(--ink)' }}>{h.buildingsCount}</b> building{h.buildingsCount === 1 ? '' : 's'} (≥150k each) → <b style={{ color: 'var(--ink)' }}>{mult}×</b> payout multiplier.</span>
                  : <span>No buildings yet — holding ≥150,000 of any building token adds a payout multiplier.</span>}
              </div>

              {D.rounds.length > 0 && <>
                <div className="eyebrow" style={{ marginTop: 22 }}>Income by round (est.)</div>
                <div style={{ display: 'flex', alignItems: 'flex-end', gap: 6, height: 56, marginTop: 10 }}>
                  {rounds.slice().reverse().map((rd) => (
                    <div key={rd.round} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4 }}>
                      <div style={{ width: '100%', height: Math.max(4, 44 * rd.sol / maxR), background: 'linear-gradient(180deg,var(--grass-l),var(--grass-d))', borderRadius: 4 }} title={rd.sol + ' SOL'}></div>
                      <span className="mono faint" style={{ fontSize: 9 }}>#{rd.round}</span>
                    </div>
                  ))}
                </div>
              </>}
            </div>
          </div>
        </div>
      </Scrim>
    );
  }

  /* ---------- BUILDING modal — REAL pump.fun stats (MC/holders/price) ---------- */
  function BuildingModal({ building, onClose }) {
    const b = building;
    const stageLabel = b.stage === 'amm' ? 'Migrated · AMM' : b.stage === 'bc' ? 'Bonding curve' : 'Not live yet';
    const priceStr = b.priceSol > 0 ? b.priceSol.toExponential(2) + ' SOL' : '—';
    return (
      <Scrim onClose={onClose} w={680}>
        <div style={{ position: 'relative' }}>
          <CloseBtn onClose={onClose} />
          <div style={{ background: `linear-gradient(180deg, ${b.accent}22, transparent)`, padding: '20px 26px 6px', display: 'flex', gap: 22, alignItems: 'center' }}>
            <div style={{ width: 180, height: 180, flexShrink: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', border: '2.5px solid var(--black)', boxShadow: 'var(--shadow)', background: 'var(--surface3)', padding: 10 }}><Tile kind="building" building={b.key} size={158} /></div>
            <div>
              <span className="mono" style={{ fontSize: 13, fontWeight: 700, color: b.accent }}>${b.ticker}</span>
              <h2 style={{ fontSize: 28, marginTop: 4 }}>{b.name}</h2>
              <div className="faint" style={{ fontSize: 13, marginTop: 4 }}>{b.hook}</div>
              <p style={{ fontSize: 13.5, marginTop: 10, maxWidth: 320, color: 'var(--ink2)' }}>{b.narr}</p>
            </div>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 10, padding: '14px 26px' }}>
            <Stat label="Market cap" value={b.marketCapUsd > 0 ? F.usd(b.marketCapUsd) : '—'} sub="live · pump.fun" />
            <Stat label="Holders" value={b.holderCount} />
            <Stat label="Price" value={priceStr} sub={stageLabel} />
          </div>
          <div className="hr"></div>
          <div style={{ padding: '14px 26px' }}>
            <div className="eyebrow" style={{ marginBottom: 8 }}>How it boosts your land</div>
            <p className="faint" style={{ fontSize: 13 }}>Hold <b className="mono" style={{ color: 'var(--ink)' }}>≥ 150,000 ${b.ticker}</b> to add <b style={{ color: 'var(--ink)' }}>+1 building</b> to your wallet (max 3 across all buildings), multiplying your share of the daily SOL payouts by up to 2.5×. Buildings are a live balance — they follow your wallet, not a fixed NFT.</p>
          </div>
          <div className="hr"></div>
          <div style={{ padding: '14px 26px', display: 'flex', gap: 10 }}>
            <a className="btn btn-primary" style={{ flex: 1, justifyContent: 'center' }} href={'https://pump.fun/coin/' + b.mint} target="_blank" rel="noreferrer">Buy ${b.ticker} on pump.fun ↗</a>
            <button className="btn btn-ghost" onClick={onClose}>Close</button>
          </div>
        </div>
      </Scrim>
    );
  }

  /* ---------- ACQUIRE flow ---------- */
  const MIN = 100000, MAX = 250000000;
  function areaFor(vol) { return Math.max(1, Math.round(Math.pow(vol / 1000000, 0.62) * 1.7) + (vol >= 100000000 ? 6 : 0)); }
  function AcquireModal({ wallet, onConnect, onClose }) {
    const [step, setStep] = React.useState(wallet ? 1 : 0);
    const [vol, setVol] = React.useState(2500000);
    React.useEffect(() => { if (wallet && step === 0) setStep(1); }, [wallet]);
    const rar = D.rarityOf(vol);
    const cells = areaFor(vol);
    const share = cells / (D.stats.ownedCells + cells) * 100;
    const daily = D.stats.currentPool * cells / (D.stats.ownedCells + cells);
    const pct = (Math.log(vol) - Math.log(MIN)) / (Math.log(MAX) - Math.log(MIN)) * 100;
    const setFromSlider = (p) => { const v = Math.exp(Math.log(MIN) + (p / 100) * (Math.log(MAX) - Math.log(MIN))); setVol(Math.round(v / 1000) * 1000); };

    return (
      <Scrim onClose={onClose} w={560}>
        <div style={{ position: 'relative' }}>
          <CloseBtn onClose={onClose} />
          {/* progress steps */}
          <div style={{ display: 'flex', gap: 6, padding: '18px 26px 0' }}>
            {['Wallet', 'Amount', 'Confirm'].map((l, i) => (
              <div key={l} style={{ flex: 1 }}>
                <div style={{ height: 4, borderRadius: 999, background: i <= step ? 'var(--grass)' : 'var(--cream-d)' }}></div>
                <div className="mono" style={{ fontSize: 10, marginTop: 6, color: i <= step ? 'var(--ink)' : 'var(--muted)', letterSpacing: '.04em' }}>{i + 1}. {l}</div>
              </div>
            ))}
          </div>

          {step === 0 && (
            <div style={{ padding: '26px', textAlign: 'center' }}>
              <div style={{ width: 130, height: 130, margin: '4px auto 10px', border: '2.5px solid var(--black)', boxShadow: 'var(--shadow)', background: 'var(--surface3)' }}><Tile kind="parcel" rarity="legendary" size={125} seed={7} /></div>
              <h2 style={{ fontSize: 24 }}>Connect your wallet</h2>
              <p className="faint" style={{ fontSize: 13.5, margin: '8px auto 20px', maxWidth: 360 }}>Ownership of the territory is bound to your Solana address. Phantom is supported.</p>
              <button className="btn btn-primary btn-block" onClick={() => { onConnect(); setStep(1); }}>Connect Phantom</button>
            </div>
          )}

          {step === 1 && (
            <div style={{ padding: '22px 26px 26px' }}>
              <h2 style={{ fontSize: 22 }}>How much $LAND to hold?</h2>
              <p className="faint" style={{ fontSize: 13, marginTop: 4 }}>Your map territory is your $LAND balance — just buy and hold. More tokens → more land → bigger share of the daily SOL payouts.</p>

              <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginTop: 22 }}>
                <span className="tnum" style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 34, letterSpacing: '-.03em' }}>{vol.toLocaleString('en-US')}</span>
                <span className="mono faint" style={{ fontSize: 13 }}>$LAND</span>
              </div>
              <input type="range" className="slider" min="0" max="100" step="0.1" value={pct} style={{ '--p': pct + '%', marginTop: 14 }} onChange={(e) => setFromSlider(+e.target.value)} />
              <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 6 }}>
                <span className="mono faint" style={{ fontSize: 10.5 }}>min {F.land(MIN)}</span>
                <span className="mono faint" style={{ fontSize: 10.5 }}>{F.land(MAX)}</span>
              </div>

              {/* live preview */}
              <div style={{ display: 'grid', gridTemplateColumns: '120px 1fr', gap: 16, marginTop: 20, alignItems: 'center', padding: 14, borderRadius: 14, border: '1px solid var(--line)', background: 'var(--surface3)' }}>
                <div style={{ height: 110, display: 'flex', alignItems: 'center', justifyContent: 'center', border: '2.5px solid var(--black)', background: 'var(--surface3)' }}>
                  <Tile kind="parcel" rarity={rar.key} size={104} seed={Math.round(vol / 1000)} />
                </div>
                <div style={{ display: 'grid', gap: 9 }}>
                  <PreviewRow label="Territory" value={cells + ' ' + (cells === 1 ? 'cell' : 'cells')} />
                  <PreviewRow label="Rarity" value={<window.RarityBadge rk={rar.key} size="sm" />} />
                  <PreviewRow label="Payout share" value={'≈ ' + share.toFixed(2) + '%'} />
                  <PreviewRow label="Est. / round" value={'≈ ' + daily.toFixed(2) + ' SOL'} accent />
                </div>
              </div>

              <div style={{ display: 'flex', gap: 9, marginTop: 18 }}>
                {[500000, 5000000, 25000000, 100000000].map(v => (
                  <button key={v} className="btn btn-ghost btn-sm" style={{ flex: 1, padding: 0 }} onClick={() => setVol(v)}>{F.land(v)}</button>
                ))}
              </div>
              <button className="btn btn-primary btn-block" style={{ marginTop: 16 }} onClick={() => setStep(2)}>Continue →</button>
            </div>
          )}

          {step === 2 && (
            <div style={{ padding: '26px', textAlign: 'center' }}>
              <div style={{ width: 150, height: 150, margin: '0 auto 10px', border: '2.5px solid var(--black)', boxShadow: 'var(--shadow)', background: 'var(--surface3)' }}><Tile kind="parcel" rarity={rar.key} size={145} seed={Math.round(vol / 1000)} /></div>
              <div style={{ display: 'inline-flex', marginBottom: 8 }}><window.RarityBadge rk={rar.key} /></div>
              <h2 style={{ fontSize: 24 }}>Claim your land</h2>
              <p className="faint" style={{ fontSize: 13.5, margin: '8px auto 18px', maxWidth: 380 }}>Hold <b className="mono" style={{ color: 'var(--ink)' }}>{vol.toLocaleString('en-US')} $LAND</b> and you claim <b style={{ color: 'var(--ink)' }}>{cells} {cells === 1 ? 'cell' : 'cells'}</b> of territory with a ≈ {share.toFixed(2)}% share of the payouts. Territory tracks your live balance — buy on pump.fun and you appear on the map automatically.</p>
              <div style={{ display: 'flex', gap: 10 }}>
                <button className="btn btn-ghost" style={{ flex: 1, justifyContent: 'center' }} onClick={() => setStep(1)}>Back</button>
                <a className="btn btn-primary" style={{ flex: 2, justifyContent: 'center' }} href={'https://pump.fun/coin/' + D.LAND_MINT} target="_blank" rel="noreferrer">Buy $LAND on pump.fun ↗</a>
              </div>
              <div className="faint" style={{ fontSize: 11, marginTop: 12 }}>$LAND launches on pump.fun — the buy link goes live the moment the token is up.</div>
            </div>
          )}
        </div>
      </Scrim>
    );
  }
  function PreviewRow({ label, value, accent }) {
    return (
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 8 }}>
        <span className="faint" style={{ fontSize: 12, whiteSpace: 'nowrap' }}>{label}</span>
        <span className="mono tnum" style={{ fontSize: 12.5, fontWeight: 700, color: accent ? 'var(--grass-d)' : 'var(--ink)', whiteSpace: 'nowrap' }}>{value}</span>
      </div>
    );
  }
  window.Modals = { ParcelModal, BuildingModal, AcquireModal };
})();
