// Main app
const { useState, useEffect, useMemo } = React;

const TWEAK_DEFAULTS = {
  showScoreboard: true,
  density: 'comfortable',
};

const SEG_VALUE = { d1am: 0.5, d1pm: 1, d2: 0.5, d3: 1 };
function computeLiveScore(scores) {
  let usa = 0, euro = 0;
  function add(v, val) {
    if (v === 'usa') usa += val;
    else if (v === 'euro') euro += val;
    else if (v === 'halve') { usa += val / 2; euro += val / 2; }
  }
  for (const day of ['d1am', 'd2', 'd3']) {
    const val = SEG_VALUE[day];
    for (const m of ['m1', 'm2', 'm3', 'm4']) {
      const seg = scores?.[day]?.[m] || {};
      add(seg.f, val); add(seg.b, val); add(seg.total, val);
    }
  }
  const v = SEG_VALUE.d1pm;
  const dpm = scores?.d1pm || {};
  add(dpm.f, v); add(dpm.b, v); add(dpm.total, v);
  const isLive = !!scores?.live;
  const anyD3 = ['m1','m2','m3','m4'].some(m => Object.values(scores?.d3?.[m] || {}).some(x => x));
  const anyD2 = ['m1','m2','m3','m4'].some(m => Object.values(scores?.d2?.[m] || {}).some(x => x));
  const anyD1pm = Object.values(scores?.d1pm || {}).some(x => x);
  const anyD1am = ['m1','m2','m3','m4'].some(m => Object.values(scores?.d1am?.[m] || {}).some(x => x));
  let label;
  if (!isLive) label = 'PRE-TOURNAMENT';
  else if (anyD3) label = 'LIVE · DAY 3';
  else if (anyD2) label = 'AFTER DAY 2';
  else if (anyD1pm) label = 'AFTER DAY 1';
  else if (anyD1am) label = 'DAY 1';
  else label = 'LIVE';
  return { usa, euro, label, live: isLive };
}

function App() {
  const t = TWEAK_DEFAULTS;
  const [activeDay, setActiveDay] = useState('d1am');
  const [score, setScore] = useState({ usa: 0, euro: 0, label: 'PRE-TOURNAMENT', live: false });
  const day = DAYS.find(d => d.id === activeDay);

  useEffect(() => {
    let cancelled = false;
    function load() {
      fetch('/api/score', { cache: 'no-store' })
        .then(r => r.ok ? r.json() : null)
        .then(data => { if (!cancelled && data) setScore(computeLiveScore(data)); })
        .catch(() => {});
    }
    load();
    const id = setInterval(load, 30000);
    return () => { cancelled = true; clearInterval(id); };
  }, []);

  const usaLeads = score.usa > score.euro;
  const euroLeads = score.euro > score.usa;
  const tied = score.usa === score.euro;

  return (
    <div className={`app density-${t.density}`}>
      {/* HERO */}
      <header className="hero">
        <div className="hero-bg">
          <div className="hero-grid" />
        </div>

        <div className="hero-top">
          <div className="hero-top-left mono">EST · MMXX  ·  V · IV</div>
          <div className="hero-top-right mono">MURRELLS INLET · SC</div>
        </div>

        <div className="hero-main">
          <div className="hero-crest">
            <Crest size={180} />
          </div>
          <div className="hero-title">
            <div className="hero-eyebrow">THE ANNUAL</div>
            <h1 className="hero-headline">
              <span>Law</span>
              <span className="amp">·</span>
              <span>Invitational</span>
            </h1>
            <div className="hero-version">— V<span className="roman">IV</span> —</div>
          </div>
          <div className="hero-crest right">
            <Crest size={180} />
          </div>
        </div>

        <div className="hero-tag">
          <div className="welcome">Welcome to <em>Dirty Myrtle</em></div>
          <div className="welcome-sub">Where your balls fly the same distance but your dollar goes a lot farther</div>
        </div>

        <div className="hero-stats">
          <Stat num="16" lbl="MEN" />
          <Stat num="4" lbl="ROUNDS" />
          <Stat num="27" lbl="POINTS" />
          <Stat num="1" lbl="CUP" />
        </div>

        <div className="hero-dates">
          <span className="mono">May 13–17, 2026</span>
          <span className="dot-sep" />
          <span className="mono">Murrells Inlet, SC</span>
        </div>
      </header>

      {/* SCOREBOARD */}
      {t.showScoreboard && (
        <section className="scoreboard">
          <div className={`scoreboard-rule ${score.live ? 'live' : ''}`}><span className="mono">{score.live ? 'THE CUP · LIVE' : 'THE CUP'}</span><span className="status-dot" /></div>
          <div className="scoreboard-main">
            <div className={`scoreside usa ${usaLeads ? 'leading' : ''}`}>
              <div className="scoreside-flag-usa">
                <div className="usa-stripes">
                  {[...Array(7)].map((_, i) => <div key={i} className={`stripe ${i % 2 === 0 ? 'red' : 'white'}`} />)}
                </div>
                <div className="usa-canton" />
              </div>
              <div className="scoreside-text">
                <div className="scoreside-name">USA</div>
                <div className="scoreside-hcp mono">HCP 136</div>
              </div>
              <div className="scoreside-num">{score.usa}</div>
            </div>

            <div className="scoreboard-mid">
              <div className="needed">14<span>·needed</span></div>
              <div className="status-text">{score.label}</div>
              <div className="retain">13.5–13.5 · retains</div>
            </div>

            <div className={`scoreside euro ${euroLeads ? 'leading' : ''}`}>
              <div className="scoreside-num">{score.euro}</div>
              <div className="scoreside-text right">
                <div className="scoreside-name">EUROPE</div>
                <div className="scoreside-hcp mono">HCP 143</div>
              </div>
              <div className="scoreside-flag-euro">
                <div className="euro-circle">
                  {[...Array(12)].map((_, i) => {
                    const angle = (i / 12) * Math.PI * 2 - Math.PI / 2;
                    const x = 50 + 36 * Math.cos(angle);
                    const y = 50 + 36 * Math.sin(angle);
                    return (
                      <svg key={i} className="euro-star" style={{ left: `${x}%`, top: `${y}%` }} viewBox="0 0 10 10" width="10" height="10">
                        <polygon points="5,0 6,3.5 10,3.5 7,6 8,10 5,7.5 2,10 3,6 0,3.5 4,3.5" fill="#c9a14a" />
                      </svg>
                    );
                  })}
                </div>
              </div>
            </div>
          </div>
          {tied && score.usa > 0 && (
            <div className="scoreboard-foot">All square. Anything can happen.</div>
          )}
        </section>
      )}
      {t.showScoreboard && (
        <a href="/scoreboard/" className="scoreboard-detail-link mono">VIEW DETAILED SCOREBOARD →</a>
      )}

      {/* TEAMS */}
      <section className="section teams-section">
        <SectionHeader eyebrow="The Teams" title="Sixteen men. Two flags. One trophy." sub="No mulligans. No alibis." />
        <div className="teams-grid">
          <TeamCard team={TEAMS.usa} side="usa" />
          <TeamCard team={TEAMS.euro} side="euro" />
        </div>
      </section>

      {/* CUP / FORMAT */}
      <section className="section cup-section">
        <SectionHeader eyebrow="The Cup" title="27 points up for grabs." sub="14 wins it. 13.5–13.5 retains. Day 3 carries double the weight — nobody's mathematically cooked until the closing nine." />

        <div className="schedule-table">
          <div className="schedule-head">
            <div>When</div>
            <div>Round</div>
            <div>Format</div>
            <div className="ta-r">Points</div>
          </div>
          {SCHEDULE.map((s, i) => (
            <div key={i} className={`schedule-row ${i === 3 ? 'decider' : ''}`}>
              <div className="mono">{s.when}</div>
              <div><strong>{s.round}</strong></div>
              <div>{s.format}</div>
              <div className="ta-r pts">{s.points}</div>
            </div>
          ))}
          <div className="schedule-total">
            <div></div>
            <div></div>
            <div className="mono">TOTAL</div>
            <div className="ta-r pts total">27</div>
          </div>
        </div>

        <div className="scoring-explainer">
          <div className="se-block">
            <div className="se-num">3</div>
            <div className="se-label">SEGMENTS<br/>PER MATCH</div>
            <p>Every match-play match splits into <strong>Front 9</strong>, <strong>Back 9</strong>, and <strong>Full 18</strong>. Win all three, take all the points. Tied segment = halved.</p>
          </div>
          <div className="se-block">
            <div className="se-num">1.5</div>
            <div className="se-label">PTS / MATCH<br/>DAYS 1–2</div>
            <p><span className="mono">0.5 / 0.5 / 0.5</span><br/>Standard segment scoring across the first three rounds.</p>
          </div>
          <div className="se-block decider">
            <div className="se-num">3</div>
            <div className="se-label">PTS / MATCH<br/>DAY 3</div>
            <p><span className="mono">1 / 1 / 1</span><br/>Saturday is double-weighted. The closing day is where this thing is decided.</p>
          </div>
        </div>

        <div className="format-cards-intro">
          <div className="fci-eyebrow mono">GROUP'S CHOICE</div>
          <p>On the three regular match-play days, each group of 4 (one USA pair vs. one Euro pair) <strong>picks their own format on the first tee</strong> — scramble, best ball, or shamble. The four matches in a round don't have to match each other. Pick what suits your foursome.</p>
        </div>

        <div className="format-cards">
          <div className="format-card">
            <div className="fc-tag mono">FORMAT · A</div>
            <h4>Scramble</h4>
            <p>Use the <strong>Scramble Handicap</strong> shown for each match. If the natural difference between team handicaps is 3 or fewer strokes, no strokes are given. If greater, the lower-handicap team gives only enough strokes to bring the difference down to 3. Strokes taken on lowest-index holes.</p>
          </div>
          <div className="format-card">
            <div className="fc-tag mono">FORMAT · B</div>
            <h4>Best Ball</h4>
            <p>Use <strong>Best Ball / Shamble Skins</strong> strokes. Lowest HCP in the match plays scratch; everyone else gets <span className="mono">(their HCP – lowest) × 80%</span>, distributed by stroke index.</p>
          </div>
          <div className="format-card">
            <div className="fc-tag mono">FORMAT · C</div>
            <h4>Shamble</h4>
            <p>Same handicaps as Best Ball. <em>Drive scramble, then play your own ball in.</em> Best of both — generous off the tee, honest on the green.</p>
          </div>
        </div>
      </section>

      {/* DAYS */}
      <section className="section days-section">
        <SectionHeader eyebrow="The Schedule" title="Four rounds. Four courses. One trophy." />

        <div className="day-tabs">
          {DAYS.map(d => (
            <button
              key={d.id}
              className={`day-tab ${activeDay === d.id ? 'on' : ''} ${d.decider ? 'decider' : ''}`}
              onClick={() => setActiveDay(d.id)}
            >
              <div className="dt-short">{d.short}</div>
              <div className="dt-pts mono">{d.points} PTS</div>
            </button>
          ))}
        </div>

        <DayPanel day={day} />
      </section>

      {/* FOOTER */}
      <footer className="site-foot">
        <div className="foot-crest"><Crest size={70} /></div>
        <div className="foot-text">
          <div className="foot-line">Questions? Hit up the <strong>Supreme Leader</strong>.</div>
          <div className="foot-meta mono">ANNUAL LAW INVITATIONAL · V·IV · MURRELLS INLET · MMXXVI</div>
        </div>
        <div className="foot-crest"><Crest size={70} /></div>
      </footer>

    </div>
  );
}

function Stat({ num, lbl }) {
  return (
    <div className="hero-stat">
      <div className="hs-num">{num}</div>
      <div className="hs-lbl mono">{lbl}</div>
    </div>
  );
}

function SectionHeader({ eyebrow, title, sub }) {
  return (
    <div className="section-head">
      <div className="eyebrow gold">{eyebrow}</div>
      <h2 className="section-title">{title}</h2>
      {sub && <p className="section-sub">{sub}</p>}
    </div>
  );
}

function TeamCard({ team, side }) {
  const sorted = [...team.players].sort((a, b) => a.hcp - b.hcp);
  return (
    <div className={`team-card ${side}`}>
      <div className="team-card-bar" />
      <div className="team-card-head">
        <div className="team-name">{team.name}</div>
        <div className="team-hcp mono">HCP {team.hcp}</div>
      </div>
      <div className="team-roster">
        {sorted.map((p, i) => (
          <div key={i} className="player-row">
            <div className="player-num mono">{String(i + 1).padStart(2, '0')}</div>
            <div className="player-name">{p.name}</div>
            <div className="player-hcp">
              <div className="hcp-bar"><div className="hcp-bar-fill" style={{ width: `${(p.hcp / 24) * 100}%` }} /></div>
              <div className="hcp-num mono">{p.hcp}</div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
