// countdown-app.jsx — the REAL HSC Countdown mounted by countdown.html.
// Honest version of the idea-5-cram.jsx mock: a true days-to-HSC ring (anchored
// to the 2026 NSW HSC written-exam start), this-week study activity from real
// question_attempts, overall mastery from topic_mastery, and a weak-topic queue
// from the existing get_weak_topics RPC. No fabricated "adaptive plan", no fake
// AI-marked sessions, no invented XP.
//
// Deliberately does NOT reuse ideas/idea-5-cram.jsx (CountdownPath), which is a
// hardcoded design mock still used by the ideas gallery.

// 2026 NSW HSC written exams begin Tue 13 Oct 2026 (English Paper 1), morning.
// NSW is on daylight time (AEDT, UTC+11) in October.
const HSC_EXAM_START = new Date('2026-10-13T09:00:00+11:00');
const HSC_WINDOW_DAYS = 180; // ring fills as the exam approaches

function daysUntilHSC() {
  const ms = HSC_EXAM_START.getTime() - Date.now();
  return Math.max(0, Math.ceil(ms / 86400000));
}

const CD_DOW = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];

function cdPrettyTopic(t) {
  return (t || '').replace(/-/g, ' ').replace(/\b\w/g, function (c) { return c.toUpperCase(); });
}

const CD_SUBJECT_LABELS = {
  'biology': 'Biology', 'chemistry': 'Chemistry', 'physics': 'Physics',
  'maths-advanced': 'Maths Adv', 'maths-standard': 'Maths Std', 'maths-ext1': 'Maths Ext 1',
};
// level 0..3 -> queue swatch colour (mirrors the mastery heat scale)
const CD_LEVEL_COLOR = ['#c47b8a', '#d6a85f', '#7eb0d8', '#6b9b7c'];

function HSCCountdown() {
  const days = daysUntilHSC();
  const ringPct = Math.max(0, Math.min(1, 1 - days / HSC_WINDOW_DAYS));

  const [status, setStatus]   = React.useState('loading'); // loading|ready|signedout|error
  const [week, setWeek]       = React.useState([]);
  const [overall, setOverall] = React.useState(null);      // overall mastery pct
  const [weak, setWeak]       = React.useState([]);
  const [dueCount, setDueCount] = React.useState(0);       // review cards due today

  React.useEffect(function () {
    let alive = true;
    const db   = window.HSC && window.HSC.supabase;
    const auth = window.HSC && window.HSC.auth;
    if (!db || !auth || !auth.ready) { setStatus('signedout'); return; }

    auth.ready.then(async function () {
      if (!alive) return;
      if (!(auth.getUser && auth.getUser())) { setStatus('signedout'); return; }
      try {
        const since = new Date(); since.setHours(0, 0, 0, 0); since.setDate(since.getDate() - 6);
        const today = new Date(); today.setHours(0, 0, 0, 0);
        const todayISO = today.getFullYear() + '-' + String(today.getMonth() + 1).padStart(2, '0') + '-' + String(today.getDate()).padStart(2, '0');
        const [att, prog, wk, due] = await Promise.all([
          db.from('question_attempts').select('created_at,correct').gte('created_at', since.toISOString()),
          db.rpc('get_progress'),
          db.rpc('get_weak_topics', { p_subject: null, p_limit: 6 }),
          db.from('review_cards').select('question_id', { count: 'exact', head: true }).lte('due_at', todayISO),
        ]);
        if (!alive) return;
        setDueCount(due && typeof due.count === 'number' ? due.count : 0);

        // ---- this-week activity strip (rolling 7 days ending today) ----
        const todayKey = new Date(); todayKey.setHours(0, 0, 0, 0);
        const buckets = [];
        for (let i = 6; i >= 0; i--) {
          const d = new Date(todayKey); d.setDate(d.getDate() - i);
          buckets.push({ key: d.toDateString(), name: CD_DOW[d.getDay()], num: d.getDate(), count: 0, isToday: i === 0 });
        }
        (att.data || []).forEach(function (a) {
          const d = new Date(a.created_at); d.setHours(0, 0, 0, 0);
          const b = buckets.find(function (x) { return x.key === d.toDateString(); });
          if (b) b.count++;
        });
        setWeek(buckets);

        // ---- overall mastery ----
        const overallRow = (prog.data || []).find(function (r) { return r.subject === 'overall'; });
        setOverall(overallRow ? overallRow.mastery_pct : 0);

        // ---- weak-topic queue ----
        setWeak(wk.data || []);
        setStatus('ready');
      } catch (e) {
        console.warn('[HSC] countdown load failed', e);
        if (alive) setStatus('error');
      }
    });

    return function () { alive = false; };
  }, []);

  const activeDays = week.filter(function (d) { return d.count > 0; }).length;

  return (
    <div className="cr-wrap">
      <div className="cr-main">
        {/* header: days-to-HSC ring (works signed-out too) */}
        <div className="cr-head">
          <div className="cr-head-ring">
            <CdRing days={days} pct={ringPct}/>
          </div>
          <div className="cr-head-info">
            <h2>HSC exams begin · <em>{days} days</em></h2>
            <p>Counting down to the first 2026 NSW HSC written exam (13 October). Keep your
               streak alive and chip away at your weak topics below — every quiz you do
               updates your mastery.</p>
          </div>
          <div className="cr-head-bigday">
            <strong>{days}</strong>
            <small>days to go</small>
          </div>
        </div>

        {status === 'signedout' && (
          <div className="cr-today" style={{ textAlign: 'center', padding: '32px 24px' }}>
            <p style={{ color: 'var(--adv-muted)', marginBottom: 16 }}>
              Log in to see your study streak, weak-topic queue and mastery progress toward the HSC.
            </p>
            <a className="sm-cta primary" href="auth/login.html" style={{ display: 'inline-flex', textDecoration: 'none' }}>
              <Icon name="play"/><div>Log in</div>
            </a>
          </div>
        )}

        {status === 'error' && (
          <div className="cr-today" style={{ textAlign: 'center', padding: '32px 24px' }}>
            <p style={{ color: 'var(--adv-muted)' }}>Couldn't load your study data right now. Please refresh.</p>
          </div>
        )}

        {status === 'ready' && (
          <React.Fragment>
            <div className="cr-week-label">THIS WEEK · {activeDays} / 7 days studied</div>
            <div className="cr-week">
              {week.map(function (d, i) {
                const state = d.isToday ? 'today' : (d.count > 0 ? 'done' : 'miss');
                return (
                  <div key={i} className={'cr-day ' + state}>
                    {d.count > 0 && <div className="cr-day-tag"><Icon name="check"/></div>}
                    <div className="cr-day-name">{d.name}</div>
                    <div className="cr-day-num">{d.num}</div>
                    <div className="cr-day-bar"><i style={{ width: d.count > 0 ? '100%' : '0%' }}/></div>
                    <div className="cr-day-mins">{d.count > 0 ? (d.count + ' Q') : '—'}</div>
                  </div>
                );
              })}
            </div>

            <div className="cr-today">
              <div className="cr-today-head">
                <h3><Icon name="target"/> Study now</h3>
              </div>
              <a className="cr-sess" href="weekly-quiz.html" style={{ textDecoration: 'none' }}>
                <div className="cr-sess-mark"><Icon name="bolt"/></div>
                <div>
                  <div className="cr-sess-title">Take this week's challenge</div>
                  <div className="cr-sess-tag">15 questions · updates your mastery map</div>
                </div>
                <div className="cr-sess-go"><Icon name="chevronR"/></div>
              </a>
              {dueCount > 0 && (
                <a className="cr-sess" href="review-deck.html" style={{ textDecoration: 'none' }}>
                  <div className="cr-sess-mark"><Icon name="check"/></div>
                  <div>
                    <div className="cr-sess-title">Review {dueCount} due card{dueCount === 1 ? '' : 's'}</div>
                    <div className="cr-sess-tag">Spaced repetition · from questions you missed</div>
                  </div>
                  <div className="cr-sess-go"><Icon name="chevronR"/></div>
                </a>
              )}
              {weak.slice(0, 2).map(function (w, i) {
                return (
                  <a key={i} className="cr-sess" href={'/subjects/' + w.subject + '/index.html'} style={{ textDecoration: 'none' }}>
                    <div className="cr-sess-mark">{i + 1}</div>
                    <div>
                      <div className="cr-sess-title">Sharpen: {cdPrettyTopic(w.topic)}</div>
                      <div className="cr-sess-tag">{CD_SUBJECT_LABELS[w.subject] || w.subject} · {w.pct}% mastery</div>
                    </div>
                    <div className="cr-sess-go"><Icon name="chevronR"/></div>
                  </a>
                );
              })}
              {weak.length === 0 && (
                <div className="cr-today-foot">
                  <span>No weak topics tracked yet — do a quiz and your weakest areas will surface here.</span>
                </div>
              )}
            </div>
          </React.Fragment>
        )}
      </div>

      {/* side */}
      <div className="cr-side">
        <div className="cr-bigring">
          <div className="cr-bigring-svg">
            <CdRingDark days={overall == null ? '—' : overall + '%'} pct={(overall || 0) / 100}/>
          </div>
          <div className="cr-bigring-lbl">OVERALL MASTERY</div>
          <div className="cr-bigring-sub">
            {status === 'ready'
              ? 'Across every topic you\'ve practised'
              : 'Log in to track your mastery'}
          </div>
        </div>

        {status === 'ready' && weak.length > 0 && (
          <div className="cr-weak">
            <h4>Your weak-topic queue</h4>
            {weak.map(function (w, i) {
              return (
                <div key={i} className="cr-weak-row">
                  <div className="cr-weak-mast" style={{ background: CD_LEVEL_COLOR[w.level] || '#c47b8a' }}>
                    {w.pct}
                  </div>
                  <div className="cr-weak-name">
                    {cdPrettyTopic(w.topic)}
                    <small>{CD_SUBJECT_LABELS[w.subject] || w.subject}</small>
                  </div>
                  <div className="cr-weak-time">{w.due_count ? (w.due_count + ' due') : ''}</div>
                </div>
              );
            })}
          </div>
        )}
      </div>
    </div>
  );
}

// Days-to-HSC ring (light theme, header)
function CdRing({ days, pct }) {
  const r = 38;
  const c = 2 * Math.PI * r;
  return (
    <svg viewBox="0 0 88 88" width="88" height="88">
      <circle cx="44" cy="44" r={r} fill="none" stroke="rgba(45,49,66,0.10)" strokeWidth="7"/>
      <circle cx="44" cy="44" r={r} fill="none" stroke="#c47b8a" strokeWidth="7" strokeLinecap="round"
        strokeDasharray={(c * pct) + ' ' + c} transform="rotate(-90 44 44)"/>
      <text x="44" y="46" textAnchor="middle" fontSize="22" fontWeight="800" fill="#2d3142">{days}</text>
      <text x="44" y="62" textAnchor="middle" fontSize="9" fontWeight="700" letterSpacing="1.4" fill="#8a8079">DAYS</text>
    </svg>
  );
}

// Overall-mastery ring (dark side panel)
function CdRingDark({ days, pct }) {
  const r = 56;
  const c = 2 * Math.PI * r;
  return (
    <svg viewBox="0 0 130 130" width="130" height="130">
      <circle cx="65" cy="65" r={r} fill="none" stroke="rgba(255,255,255,0.15)" strokeWidth="10"/>
      <circle cx="65" cy="65" r={r} fill="none" stroke="#d6a85f" strokeWidth="10" strokeLinecap="round"
        strokeDasharray={(c * pct) + ' ' + c} transform="rotate(-90 65 65)"/>
      <text x="65" y="68" textAnchor="middle" fontSize="26" fontWeight="800" fill="#fff">{days}</text>
    </svg>
  );
}

window.HSCCountdown = HSCCountdown;
