const { Icon } = window.PryzeDesignSystem_b2bad9;
const { USER, STATS_HISTORY, STREAK_TRAIL, STATS_EXTRA } = window.PryzeData;

function FlameIcon({ size, color, active, delay }) {
  return (
    <svg className={"flame-svg" + (active ? " flame-svg-active" : "")} style={{ animationDelay: (delay || 0) + 'ms' }} width={size} height={size} viewBox="-3 0 32 32" fill={color}>
      <g transform="translate(-417,-413)">
        <path d="M439.905,419.953 C435.52,421.203 434.717,424.748 435,427 C431.872,423.322 432,419.093 432,413 C421.968,416.783 424.301,427.688 424,431 C421.477,428.935 421,424 421,424 C418.336,425.371 417,429.031 417,432 C417,439.18 422.82,445 430,445 C437.18,445 443,439.18 443,432 C443,427.733 439.867,425.765 439.905,419.953" />
      </g>
    </svg>
  );
}

function buildAreaPath(values, w, h, padL, padR, padT, padB, maxOverride) {
  const max = maxOverride != null ? maxOverride : Math.max(...values) * 1.15;
  const min = 0;
  const step = (w - padL - padR) / (values.length - 1);
  const pts = values.map((v, i) => [padL + i * step, h - padB - ((v - min) / (max - min)) * (h - padT - padB)]);
  let line = `M${pts[0][0]},${pts[0][1]}`;
  for (let i = 1; i < pts.length; i++) {
    const [x0, y0] = pts[i - 1], [x1, y1] = pts[i];
    const mx = (x0 + x1) / 2;
    line += ` C${mx},${y0} ${mx},${y1} ${x1},${y1}`;
  }
  const area = line + ` L${pts[pts.length - 1][0]},${h - padB} L${pts[0][0]},${h - padB} Z`;
  return { line, area, pts, max };
}

function niceMax(raw, ticks) {
  if (raw <= 0) return ticks;
  const rawStep = raw / ticks;
  const pow = Math.pow(10, Math.floor(Math.log10(rawStep)));
  const cands = [1, 2, 2.5, 5, 10].map(s => s * pow);
  const step = cands.find(c => c >= rawStep) || 10 * pow;
  return step * ticks;
}

const PERIODS = [{ key: 'week', label: 'W', full: 'Week' }, { key: 'month', label: 'M', full: 'Month' }, { key: 'year', label: 'Y', full: 'Year' }];
const RANGE_TITLES = { week: 'Oct 05 – Oct 11 2025', month: 'Oct 2025', year: 'Jan – Dec 2025' };

function StatsChart({ mode, onModeChange }) {
  const [period, setPeriod] = React.useState('month');
  const [active, setActive] = React.useState(null);
  const barsRef = React.useRef(null);
  const data = STATS_HISTORY[period];
  const values = mode === 'points' ? data.points : data.goals;
  const max = Math.max(...values) * 1.06;
  const total = values.reduce((a, b) => a + b, 0);
  const bestIdx = values.indexOf(Math.max(...values));
  const shown = active != null ? active : bestIdx;
  const unit = mode === 'points' ? 'pts' : 'goals';
  const filled = values.filter(v => v > 0);
  const perLabel = period === 'year' ? 'mo' : 'day';
  const avg = filled.length ? Math.round(filled.reduce((x, y) => x + y, 0) / filled.length) : 0;
  const half = Math.floor(values.length / 2);
  const firstHalf = values.slice(0, half).reduce((x, y) => x + y, 0);
  const secondHalf = values.slice(half).reduce((x, y) => x + y, 0);
  const trendPct = firstHalf ? Math.round(((secondHalf - firstHalf) / firstHalf) * 100) : 0;
  const labelAt = i => (period === 'month' ? 'Oct ' + data.labels[i] : data.labels[i]);
  const insight = active != null
    ? { lead: labelAt(active) + ': ' + values[active].toLocaleString() + ' ' + unit,
        tail: avg ? (values[active] >= avg ? (values[active] / avg).toFixed(1) + '× your ' + perLabel + 'ly average' : Math.round((1 - values[active] / avg) * 100) + '% below your average') : '' }
    : { lead: avg.toLocaleString() + ' ' + unit + ' / ' + perLabel + ' average',
        tail: (trendPct >= 0 ? 'up ' : 'down ') + Math.abs(trendPct) + '% vs. earlier · best ' + labelAt(bestIdx) };

  React.useEffect(() => { const el = barsRef.current; if (el) el.scrollLeft = el.scrollWidth; }, [period, mode]);

  return (
    <div className="vibe-card">
      <div className="vibe-orbs" aria-hidden="true"><span></span><span></span></div>
      <div className="vibe-pattern" aria-hidden="true" />
      <div className="vibe-toprow">
        <div className="vibe-seg" role="tablist" aria-label="Metric">
          <button role="tab" aria-selected={mode === 'points'} className={"vibe-seg-opt" + (mode === 'points' ? " vibe-seg-on" : "")} onClick={() => onModeChange('points')}>Points</button>
          <button role="tab" aria-selected={mode === 'goals'} className={"vibe-seg-opt" + (mode === 'goals' ? " vibe-seg-on" : "")} onClick={() => onModeChange('goals')}>Goals</button>
        </div>
        <div className="vibe-seg vibe-seg-sm" role="tablist" aria-label="Timeframe">
          {PERIODS.map(p => <button key={p.key} role="tab" aria-selected={period === p.key} aria-label={p.full} className={"vibe-seg-opt" + (period === p.key ? " vibe-seg-on" : "")} onClick={() => { setPeriod(p.key); setActive(null); }}>{p.label}</button>)}
        </div>
      </div>
      <p className="vibe-big">{total.toLocaleString()}<span className="vibe-unit">{unit} this {period === 'week' ? 'week' : period === 'month' ? 'month' : 'year'}</span></p>
      <p className="vibe-hype"><strong>{insight.lead}</strong>{insight.tail ? <span className="vibe-hype-tail"> — {insight.tail}</span> : null}</p>
      <div ref={barsRef} className={"vibe-bars vibe-bars-" + period + (mode === 'goals' ? " vibe-goals" : "")} role="group" aria-label="Tap a bar for detail">
        {values.map((v, i) => (
          <button key={i} className={"vibe-bar-col" + (i === shown ? " vibe-bar-on" : "")} onClick={() => setActive(i === active ? null : i)} aria-label={`${data.labels[i]}: ${v.toLocaleString()} ${unit}`}>
            <span className="vibe-bar-pill">{v.toLocaleString()}</span>
            <span className="vibe-bar-track"><span className="vibe-bar-fill" style={{ height: Math.max(8, (v / max) * 100) + '%' }} /></span>
            <span className="vibe-bar-day">{data.labels[i]}</span>
          </button>
        ))}
      </div>
    </div>
  );
}

function MetricCard({ icon, label, value, trend, trendUp, accent }) {
  return (
    <div className="metric-card">
      <div className="metric-top">
        <span className="metric-chip" style={{ '--mc': accent }}><Icon name={icon} weight="duotone" size={16} color={accent} /></span>
        <span className="metric-label">{label}</span>
      </div>
      <span className="metric-value">{value}{trend != null && (
        <span className={"metric-trend " + (trendUp ? "metric-trend-up" : "metric-trend-down")}>
          <Icon name={trendUp ? "trend-up" : "trend-down"} weight="bold" size={11} />{trend}
        </span>
      )}</span>
    </div>
  );
}

function StreakTrailRow() {
  const hype = USER.streak >= 7 ? "You're on fire — keep the run going" : "Building momentum, don't break it";
  return (
    <div className="streak-trail-card">
      <div className="streak-trail-orbs" aria-hidden="true"><span></span><span></span><span></span></div>
      <div className="streak-trail-pattern" aria-hidden="true" />
      <svg className="streak-illustration" viewBox="-3 0 32 32" aria-hidden="true">
        <defs>
          <linearGradient id="streakFlameGrad" x1="0" y1="32" x2="26" y2="0" gradientUnits="userSpaceOnUse">
            <stop offset="0%" stopColor="#FFD166" />
            <stop offset="55%" stopColor="#FF9F43" />
            <stop offset="100%" stopColor="#FF5A2E" />
          </linearGradient>
        </defs>
        <g transform="translate(-417,-413)">
          <path d="M439.905,419.953 C435.52,421.203 434.717,424.748 435,427 C431.872,423.322 432,419.093 432,413 C421.968,416.783 424.301,427.688 424,431 C421.477,428.935 421,424 421,424 C418.336,425.371 417,429.031 417,432 C417,439.18 422.82,445 430,445 C437.18,445 443,439.18 443,432 C443,427.733 439.867,425.765 439.905,419.953" fill="url(#streakFlameGrad)" stroke="#FFE9B0" strokeWidth="0.4" />
        </g>
      </svg>
      <div className="streak-trail-head">
        <span className="streak-trail-count">{USER.streak}</span>
        <div className="streak-trail-headtext">
          <span className="streak-trail-label">day streak</span>
          <span className="streak-trail-hype">{hype}</span>
        </div>
      </div>
      <div className="streak-trail-row">
        {STREAK_TRAIL.map((d, i) => (
          <div className="streak-trail-item" key={i}>
            <FlameIcon size={18} active={d.active} delay={i * 90} color={d.active ? '#FFE066' : 'rgba(255,255,255,.3)'} />
            <span className="streak-trail-day">{d.day}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

function StatsContent() {
  const [mode, setMode] = React.useState('points');
  return (
    <div className="stats-content">
      <p className="stats-group-title">Streak</p>
      <StreakTrailRow />
      <p className="stats-group-title">Your run</p>
      <StatsChart mode={mode} onModeChange={setMode} />
      <p className="stats-group-title">The numbers</p>
      <div className="metric-grid">
        <MetricCard accent="var(--lime-500)" icon="lightning" label="Last shift" value={STATS_EXTRA.prevWorkdayPoints} trend={"+" + STATS_EXTRA.prevWorkdayChange} trendUp />
        <MetricCard accent="var(--orange-500)" icon="currency-dollar" label="Cashed out" value={"$" + STATS_EXTRA.encashedValue} />
        <MetricCard accent="var(--violet-300)" icon="clock" label="Hours a week" value={STATS_EXTRA.avgWeeklyHours} />
        <MetricCard accent="var(--lime-500)" icon="trophy" label="Your rank" value={"#" + STATS_EXTRA.rank} trend={STATS_EXTRA.rankChange} trendUp={STATS_EXTRA.rankChange > 0} />
      </div>
    </div>
  );
}

window.PryzeStats = { StatsContent };
