// cards.jsx — the 4 card components (Clock, Weather, CRCL, USDC), front + back faces.
// Cards accept a `flipped` prop and render the flipper wrapper.

// ─────── CLOCK (no flip — tap cycles variants) ───────
const CLOCK_VARIANTS = ['digital', 'digital-sec', 'analog', 'analog-min', 'date'];

function ClockCard({ variant, onTap }) {
  const now = useClock();
  const h12 = now.getHours() % 12 || 12;
  const hh = String(h12);
  const mm = String(now.getMinutes()).padStart(2, '0');
  const ss = String(now.getSeconds()).padStart(2, '0');
  const ampm = now.getHours() >= 12 ? 'PM' : 'AM';
  const dayName = now.toLocaleDateString('en-US', { weekday: 'long', timeZone: 'America/New_York' });
  const mo = now.toLocaleDateString('en-US', { month: 'long', timeZone: 'America/New_York' });
  const dom = now.getDate();

  const variantIdx = CLOCK_VARIANTS.indexOf(variant);

  let body;
  if (variant === 'digital') {
    body = (
      <>
        <div className="dd-eyebrow">— current hour —</div>
        <div className="dd-clock-digital">{hh}<span className="dd-colon">:</span>{mm}</div>
        <div className="dd-clock-tagline">
          {dayName} {ampm.toLowerCase()},<br/>
          {timeOfDayPhrase(now.getHours())}.
        </div>
      </>
    );
  } else if (variant === 'digital-sec') {
    body = (
      <>
        <div className="dd-eyebrow">— now —</div>
        <div className="dd-clock-digital">
          {hh}<span className="dd-colon">:</span>{mm}
          <span className="dd-sec">:{ss}</span>
        </div>
        <div className="dd-clock-tagline">{dayName} · {mo} {dom}</div>
      </>
    );
  } else if (variant === 'analog') {
    body = <AnalogClock now={now} withNumerals/>;
  } else if (variant === 'analog-min') {
    body = <AnalogClock now={now} withNumerals={false}/>;
  } else if (variant === 'date') {
    body = (
      <>
        <div className="dd-eyebrow">— today —</div>
        <div className="dd-date-big">{dayName},</div>
        <div className="dd-date-huge">{mo} {dom}</div>
        <div className="dd-meta" style={{ marginTop: 10 }}>
          {hh}:{mm} {ampm} · week {weekOfYear(now)}
        </div>
      </>
    );
  }

  return (
    <div className="dd-cell dd-cell-clock" onClick={onTap}>
      <div className="dd-card-inner">{body}</div>
      <div className="dd-clock-dots" aria-hidden>
        {CLOCK_VARIANTS.map((_, i) => (
          <span key={i} className={`dd-clock-dot ${i === variantIdx ? 'active' : ''}`}/>
        ))}
      </div>
      <div className="dd-clock-hint">tap to change face</div>
    </div>
  );
}

function timeOfDayPhrase(h) {
  if (h < 5) return 'late into the night';
  if (h < 12) return 'a bright morning';
  if (h < 17) return 'the afternoon';
  if (h < 20) return 'an easy evening';
  return 'well past sundown';
}
function weekOfYear(d) {
  const s = new Date(d.getFullYear(), 0, 1);
  return Math.ceil(((d - s) / 86400000 + s.getDay() + 1) / 7);
}

function AnalogClock({ now, withNumerals }) {
  const h = now.getHours() % 12;
  const m = now.getMinutes();
  const s = now.getSeconds();
  const hAng = (h + m / 60) * 30;
  const mAng = (m + s / 60) * 6;
  const sAng = s * 6;
  const R = 60;
  return (
    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', height: '100%' }}>
      <svg width="160" height="160" viewBox="0 0 140 140">
        <circle cx="70" cy="70" r={R} fill="none" stroke="var(--rule)" strokeWidth="1.2"/>
        {/* hour marks */}
        {Array.from({length: 12}).map((_, i) => {
          const a = (i * 30 - 90) * Math.PI / 180;
          const r1 = withNumerals ? R - 2 : R - 1;
          const r2 = withNumerals ? R - 5 : R - 6;
          const x1 = 70 + Math.cos(a) * r1, y1 = 70 + Math.sin(a) * r1;
          const x2 = 70 + Math.cos(a) * r2, y2 = 70 + Math.sin(a) * r2;
          return <line key={i} x1={x1} y1={y1} x2={x2} y2={y2} stroke="var(--ink-2)" strokeWidth={i % 3 === 0 ? 1.6 : 1} strokeLinecap="round"/>;
        })}
        {withNumerals && [12, 3, 6, 9].map(n => {
          const i = n === 12 ? 0 : n;
          const a = (i * 30 - 90) * Math.PI / 180;
          const x = 70 + Math.cos(a) * (R - 14), y = 70 + Math.sin(a) * (R - 14);
          return <text key={n} x={x} y={y + 4} textAnchor="middle" fontFamily="var(--serif)" fontSize="13" fill="var(--ink-2)">{n}</text>;
        })}
        {/* hands */}
        <line x1="70" y1="70" x2="70" y2="32" stroke="var(--ink)" strokeWidth="2.4" strokeLinecap="round"
          transform={`rotate(${hAng} 70 70)`}/>
        <line x1="70" y1="70" x2="70" y2="22" stroke="var(--ink)" strokeWidth="1.6" strokeLinecap="round"
          transform={`rotate(${mAng} 70 70)`}/>
        <line x1="70" y1="74" x2="70" y2="18" stroke="var(--down)" strokeWidth="0.9" strokeLinecap="round"
          transform={`rotate(${sAng} 70 70)`}/>
        <circle cx="70" cy="70" r="2.4" fill="var(--ink)"/>
      </svg>
    </div>
  );
}

// ─────── WEATHER ───────
function WeatherCard({ data, flipped, onTap }) {
  if (!data) return <div className="dd-cell dd-cell-weather"/>;
  const { Icon, label } = wxFor(data.code, !data.isDay);
  return (
    <div className="dd-cell dd-cell-weather" onClick={onTap}>
      <div className={`dd-flipper ${flipped ? 'flipped' : ''}`}>
        {/* FRONT */}
        <div className="dd-face dd-face-front">
          <div className="dd-card-inner">
            <div className="dd-weather-main">
              <Icon size={66} color/>
              <div style={{ display: 'flex', alignItems: 'baseline', gap: 6 }}>
                <div className="dd-weather-temp">{data.tempF}°</div>
                <div className="dd-weather-condition">{label}</div>
              </div>
            </div>
            <div className="dd-weather-meta-row">
              <span><span className="dd-label">HI/LO</span>{data.hi}° / {data.lo}°</span>
              <span><span className="dd-label">WIND</span>{data.windMph} {data.windDir}</span>
              <span><span className="dd-label">☀</span>{data.sunrise}</span>
              <span><span className="dd-label">☾</span>{data.sunset}</span>
            </div>
          </div>
        </div>
        {/* BACK */}
        <div className="dd-face dd-face-back">
          <div className="dd-back" style={{ padding: 0, gap: 3 }}>
            <div className="dd-back-title">Weather    ·   Quincy   ·   next hours</div>
            <div className="dd-hourly">
              {data.hourly.slice(0, 6).map((h, i) => {
                const { Icon: HIcon } = wxFor(h.code, false);
                return (
                  <React.Fragment key={i}>
                    <div className="dd-hour">
                      <div className="dd-hour-time">{h.hour}</div>
                      <div className="dd-hour-ico"><HIcon size={24} color/></div>
                      <span className="dd-hour-t">{h.tempF}°</span>
                    </div>
                    {i < 5 && <div className="dd-hour-div"/>}
                  </React.Fragment>
                );
              })}
            </div>
            <WeeklyStrip daily={data.daily}/>
          </div>
        </div>
      </div>
    </div>
  );
}

// Seven-day strip with hi/lo bars.
function WeeklyStrip({ daily }) {
  if (!daily || !daily.length) return null;
  const allHi = daily.map(d => d.hi);
  const allLo = daily.map(d => d.lo);
  const hiMax = Math.max(...allHi);
  const loMin = Math.min(...allLo);
  const range = Math.max(1, hiMax - loMin);
  return (
    <div className="dd-weekly">
      <div className="dd-weekly-title">7-day · hi / lo</div>
      <div className="dd-weekly-row">
        {daily.slice(0, 7).map((d, i) => {
          const top = ((hiMax - d.hi) / range) * 100;
          const bot = ((d.lo - loMin) / range) * 100;
          const { Icon: DIcon } = wxFor(d.code, false);
          return (
            <div className="dd-weekly-col" key={i}>
              <div className="dd-weekly-day">{d.day}</div>
              <div className="dd-weekly-ico"><DIcon size={18} color/></div>
              <div className="dd-weekly-bar-wrap">
                <div className="dd-weekly-bar"
                  style={{ top: `${top}%`, bottom: `${bot}%` }}/>
              </div>
              <div className="dd-weekly-hi">{d.hi}°</div>
              <div className="dd-weekly-lo">{d.lo}°</div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

// ─────── CRCL ───────
function CrclCard({ data, flipped, onTap }) {
  if (!data) return <div className="dd-cell dd-cell-crcl"/>;
  const tone = !data.marketOpen ? 'grey' : (data.changeAbs >= 0 ? 'up' : 'down');
  const arrow = data.changeAbs >= 0 ? '▲' : '▼';
  const sign = data.changeAbs >= 0 ? '+' : '';
  return (
    <div className="dd-cell dd-cell-crcl" onClick={onTap}>
      <div className={`dd-flipper ${flipped ? 'flipped' : ''}`}>
        <div className="dd-face dd-face-front">
          <div className="dd-card-inner">
            <div className="dd-eyebrow">
              NYSE · CRCL
              {!data.marketOpen && <span className="dd-chip">after hrs</span>}
            </div>
            <div className={`dd-price ${tone}`}>${data.price.toFixed(2)}</div>
            <div className={`dd-change ${tone}`}>
              {arrow} {sign}${Math.abs(data.changeAbs).toFixed(2)} ({sign}{data.changePct.toFixed(2)}%)
            </div>
            {!data.marketOpen && data.extended && (
              <div className="dd-meta" style={{ marginTop: 3 }}>
                ext ${data.extended.toFixed(2)}
              </div>
            )}
          </div>
        </div>
        <div className="dd-face dd-face-back">
          <StockBack data={data} tone={tone}/>
        </div>
      </div>
    </div>
  );
}

function StockBack({ data, tone }) {
  const min = Math.min(...data.spark);
  const max = Math.max(...data.spark);
  const pts = data.spark.map((v, i) => {
    const x = (i / (data.spark.length - 1)) * 100;
    const y = 100 - ((v - min) / (max - min || 1)) * 100;
    return `${x.toFixed(1)},${y.toFixed(1)}`;
  }).join(' ');
  const stroke = tone === 'up' ? 'var(--up)' : tone === 'down' ? 'var(--down)' : 'var(--grey)';

  return (
    <div className="dd-back">
      <div className="dd-back-title">CRCL · today</div>
      <svg className="dd-spark" viewBox="0 0 100 100" preserveAspectRatio="none">
        <polyline className="line" points={pts} stroke={stroke} fill="none"/>
        <polygon className="area" points={`0,100 ${pts} 100,100`} fill={stroke}/>
      </svg>
      <div className="dd-back-grid">
        <div><div className="k">OPEN</div><div className="v">${data.open.toFixed(2)}</div></div>
        <div><div className="k">PREV</div><div className="v">${data.prev.toFixed(2)}</div></div>
        <div><div className="k">DAY HI</div><div className="v">${data.high.toFixed(2)}</div></div>
        <div><div className="k">DAY LO</div><div className="v">${data.low.toFixed(2)}</div></div>
      </div>
    </div>
  );
}

// ─────── USDC ───────
function UsdcCard({ data, flipped, onTap }) {
  if (!data) return <div className="dd-cell dd-cell-usdc"/>;
  const chgSign = data.change24h >= 0 ? '+' : '';
  return (
    <div className="dd-cell dd-cell-usdc" onClick={onTap}>
      <div className={`dd-flipper ${flipped ? 'flipped' : ''}`}>
        <div className="dd-face dd-face-front">
          <div className="dd-card-inner">
            <div className="dd-eyebrow" style={{ color: 'var(--teal)' }}>USDC · MARKET CAP</div>
            <div className="dd-price teal">{data.mktCapStr}</div>
            <div className="dd-change teal">{chgSign}{data.change24h.toFixed(2)}% · 24h</div>
            <div className="dd-meta" style={{ marginTop: 3 }}>
              <span className="dd-dot-pulse" style={{ background: 'var(--teal)' }}/>
              live
            </div>
          </div>
        </div>
        <div className="dd-face dd-face-back">
          <div className="dd-back">
            <div className="dd-back-title">USDC · Circle stablecoin</div>
            <div className="dd-back-grid">
              <div><div className="k">PRICE</div><div className="v" style={{ color: 'var(--teal)' }}>${data.price.toFixed(3)}</div></div>
              <div><div className="k">24H VOL</div><div className="v" style={{ color: 'var(--teal)' }}>${data.vol24h.toFixed(1)}B</div></div>
              <div><div className="k">SUPPLY</div><div className="v" style={{ color: 'var(--teal)' }}>{data.supply.toFixed(2)}B</div></div>
              <div><div className="k">RANK</div><div className="v" style={{ color: 'var(--teal)' }}>#{data.rank}</div></div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { ClockCard, WeatherCard, CrclCard, UsdcCard, CLOCK_VARIANTS });
