/* global React, Icon, useFairwayDispersion */

// ─── Fairways Hit detail ──────────────────────────────────────────────
// Reached from the "Fairways Hit" card in Stats → Shot stats. Shows a
// branded dispersion of the five captured tee-shot outcomes: the center
// circle is on-fairway %, and four cone segments (long / short / left /
// right) fill outward from the center in proportion to how often you miss
// that way. A month selector pages through history. Real captured data only.
//
// NOTE: names are fw-prefixed on purpose — every v1 script shares one global
// scope, and a bare `FairwayCross`/`pct` here would collide with the ones in
// match-live.jsx.

function fwPct(n, total) { return total ? Math.round((n / total) * 100) : 0; }

// Polar point in a 100×100 viewBox, angle in degrees measured from the top,
// clockwise. 0 = up, 90 = right, 180 = down, 270 = left.
function fwPolar(cx, cy, r, deg) {
  const a = (deg * Math.PI) / 180;
  return [cx + r * Math.sin(a), cy - r * Math.cos(a)];
}

// Donut wedge (annular sector) between radii r0..r1 across angles d0..d1.
function fwWedge(cx, cy, r0, r1, d0, d1) {
  const [xo0, yo0] = fwPolar(cx, cy, r1, d0);
  const [xo1, yo1] = fwPolar(cx, cy, r1, d1);
  const [xi1, yi1] = fwPolar(cx, cy, r0, d1);
  const [xi0, yi0] = fwPolar(cx, cy, r0, d0);
  const large = (d1 - d0) > 180 ? 1 : 0;
  return `M ${xo0} ${yo0} A ${r1} ${r1} 0 ${large} 1 ${xo1} ${yo1} L ${xi1} ${yi1} A ${r0} ${r0} 0 ${large} 0 ${xi0} ${yi0} Z`;
}

const FW_PCT_FONT = 22;

function FwMissArm({ value, label, style }) {
  return (
    <div style={{ position: 'absolute', textAlign: 'center', width: 76, transform: 'translate(-50%,-50%)', ...style }}>
      <div style={{ fontFamily: 'var(--font-display)', fontSize: FW_PCT_FONT, color: 'var(--forest)', lineHeight: 1 }}>{value}%</div>
      <div style={{ fontSize: 11, color: 'var(--ink)', opacity: 0.55, marginTop: 3, fontWeight: 600 }}>{label}</div>
    </div>
  );
}

function FairwayDispersion({ bucket }) {
  const hit = fwPct(bucket.hit, bucket.total);
  const R0 = 19, R1 = 38, HALF = 41; // inner/outer radius + half-angle
  // Cone axes: long=up(0) right=90 short=down(180) left=270
  const cones = [
    { key: 'long',  axis: 0,   value: bucket.long },
    { key: 'right', axis: 90,  value: bucket.right },
    { key: 'short', axis: 180, value: bucket.short },
    { key: 'left',  axis: 270, value: bucket.left },
  ];
  // Fill on a gentle (sqrt) curve of each direction's share of tee shots:
  // small misses still register, big ones don't spike — keeps it balanced.
  // The % labels always show the true share.
  const LBL = 5; // equal inset from each edge → same radius for every arm

  return (
    <div style={{ position: 'relative', width: '100%', maxWidth: 300, aspectRatio: '1 / 1', margin: '0 auto' }}>
      <svg viewBox="0 0 100 100" style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', overflow: 'visible' }}>
        <defs>
          <linearGradient id="fwFill" x1="0" y1="1" x2="0" y2="0">
            <stop offset="0%" stopColor="var(--moss)"/>
            <stop offset="100%" stopColor="var(--moss-light)"/>
          </linearGradient>
        </defs>
        {cones.map(c => {
          const prop = bucket.total ? Math.sqrt(c.value / bucket.total) : 0;
          const rFill = R0 + (R1 - R0) * prop;
          const d0 = c.axis - HALF, d1 = c.axis + HALF;
          return (
            <g key={c.key}>
              {/* faint full-length track */}
              <path d={fwWedge(50, 50, R0, R1, d0, d1)} fill="rgba(28,73,42,0.07)"/>
              {/* filled portion */}
              {c.value > 0 && <path d={fwWedge(50, 50, R0, rFill, d0, d1)} fill="url(#fwFill)"/>}
            </g>
          );
        })}
      </svg>

      {/* arm labels — one radius, one font size */}
      <FwMissArm value={fwPct(bucket.long, bucket.total)}  label="Miss Long"  style={{ top: `${LBL}%`, left: '50%' }}/>
      <FwMissArm value={fwPct(bucket.short, bucket.total)} label="Miss Short" style={{ top: `${100 - LBL}%`, left: '50%' }}/>
      <FwMissArm value={fwPct(bucket.left, bucket.total)}  label="Miss Left"  style={{ top: '50%', left: `${LBL}%` }}/>
      <FwMissArm value={fwPct(bucket.right, bucket.total)} label="Miss Right" style={{ top: '50%', left: `${100 - LBL}%` }}/>

      {/* center = on the fairway (just the %) */}
      <div style={{
        position: 'absolute', top: '50%', left: '50%', transform: 'translate(-50%,-50%)',
        width: '35%', aspectRatio: '1 / 1', borderRadius: '999px',
        background: 'linear-gradient(150deg, var(--forest) 0%, var(--moss) 100%)',
        color: 'var(--cream)', display: 'flex', alignItems: 'center', justifyContent: 'center',
        boxShadow: '0 10px 22px rgba(14,28,19,0.22)', overflow: 'hidden', textAlign: 'center',
      }}>
        <div className="grain" style={{ position: 'absolute', inset: 0, pointerEvents: 'none' }}/>
        <div style={{ position: 'relative', fontFamily: 'var(--font-display)', fontSize: 25, lineHeight: 1 }}>{hit}%</div>
      </div>
    </div>
  );
}

function FairwaysDetailScreen({ go, profile }) {
  const { loading, allTime, months } = useFairwayDispersion(profile && profile.id);
  const [sel, setSel] = React.useState('all'); // 'all' or a month key

  const periods = [{ key: 'all', label: 'All time', bucket: allTime }].concat(
    (months || []).map(m => ({ key: m.key, label: m.label, bucket: m })));
  const active = periods.find(p => p.key === sel) || periods[0];
  const bucket = active && active.bucket;
  const hasData = bucket && bucket.total > 0;

  return (
    <div style={{ background: 'var(--canvas)', minHeight: '100%', paddingBottom: 60 }}>
      {/* header */}
      <div style={{ padding: '54px 18px 6px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <button onClick={() => go({ screen: 'stats' })} style={{
          width: 40, height: 40, borderRadius: 999, background: 'var(--paper)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          border: '1px solid rgba(14,28,19,0.1)', boxShadow: 'var(--shadow-sm)',
        }}>
          <Icon.Chevron dir="left" size={13} color="var(--forest)"/>
        </button>
        <div style={{ fontSize: 10, fontFamily: 'var(--font-mono)', color: 'var(--forest)', opacity: 0.6, letterSpacing: '0.14em', textTransform: 'uppercase' }}>Fairways Hit</div>
        <div style={{ width: 40 }}/>
      </div>

      <div style={{ padding: '8px 22px 0' }}>
        <div style={{ fontFamily: 'var(--font-display)', fontSize: 30, color: 'var(--forest)', lineHeight: 1, letterSpacing: '-0.01em' }}>
          Off the tee
        </div>
        <div className="caption-serif" style={{ fontSize: 15, opacity: 0.7, marginTop: 8 }}>
          Where your tee shots finish — and which way they miss.
        </div>
      </div>

      {/* month selector */}
      {!loading && periods.length > 1 && (
        <div className="scroll-hide" style={{ display: 'flex', gap: 8, overflowX: 'auto', padding: '18px 22px 4px' }}>
          {periods.map(p => {
            const on = p.key === sel;
            return (
              <button key={p.key} onClick={() => setSel(p.key)} style={{
                flexShrink: 0, padding: '8px 14px', borderRadius: 999, cursor: 'pointer',
                fontSize: 12, fontWeight: 700, fontFamily: 'var(--font-mono)', letterSpacing: '0.02em',
                background: on ? 'var(--forest)' : 'rgba(28,73,42,0.07)',
                color: on ? 'var(--cream)' : 'var(--forest)',
                border: on ? '1px solid var(--forest)' : '1px solid rgba(28,73,42,0.14)',
              }}>{p.label}</button>
            );
          })}
        </div>
      )}

      {/* chart */}
      <div style={{ padding: '22px 22px 0' }}>
        {loading ? (
          <div style={{ textAlign: 'center', opacity: 0.5, padding: '48px 0', fontSize: 14 }}>Loading…</div>
        ) : !hasData ? (
          <div className="card" style={{ padding: '30px 24px', textAlign: 'center' }}>
            <div style={{ fontFamily: 'var(--font-display)', fontSize: 20, color: 'var(--forest)' }}>No fairway data{sel === 'all' ? ' yet' : ' this month'}.</div>
            <div style={{ fontSize: 13, opacity: 0.65, marginTop: 6 }}>Track your tee shots during scoring to build this out.</div>
          </div>
        ) : (
          <>
            <div style={{ padding: '14px 0 6px' }}>
              <FairwayDispersion bucket={bucket}/>
            </div>
            <div style={{ textAlign: 'center', fontSize: 11, fontFamily: 'var(--font-mono)', opacity: 0.5, letterSpacing: '0.04em', marginTop: 10 }}>
              Based on {bucket.total} tee shot{bucket.total === 1 ? '' : 's'}
              {sel === 'all' ? ' · all time' : ` · ${active.label}`}
            </div>
          </>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { FairwaysDetailScreen });
