// history.jsx — Riwayat (90 hari + per bulan)

const HABIT_FORMED_THRESHOLD = 80; // ≥80 dari 90 = habit terbentuk

function NinetyDayGrid({ habits, checks, today }) {
  // 90 cells, organized as 13 weeks × 7 days (91 - 1 empty)
  // Oldest at top-left, newest at bottom-right
  // Each column is a week, rows are days
  const cells = [];
  for (let i = 89; i >= 0; i--) {
    const d = new Date(today);
    d.setDate(d.getDate() - i);
    cells.push(d);
  }
  // Group into weeks
  const weeks = [];
  const firstDow = (cells[0].getDay() + 6) % 7; // Mon=0
  const grid = [];
  for (let i = 0; i < firstDow; i++) grid.push(null);
  grid.push(...cells);
  for (let i = 0; i < grid.length; i += 7) weeks.push(grid.slice(i, i + 7));

  return (
    <div className="ninety-grid-wrap">
      <div className="ninety-grid">
        {weeks.map((week, wi) => (
          <div key={wi} className="ninety-week">
            {Array.from({ length: 7 }).map((_, di) => {
              const d = week[di];
              if (!d) return <div key={di} className="ninety-cell ninety-empty"/>;
              const key = toDateKey(d);
              const dc = checks[key];
              const { total, max } = pointsForDay(habits, dc);
              const pct = max > 0 ? total / max : 0;
              const isToday = isSameDay(d, today);
              if (pct === 0) {
                return <div key={di} className={`ninety-cell ${isToday ? 'is-today' : ''}`}
                  style={{ background: 'var(--surface-2)' }} title={`${d.getDate()}/${d.getMonth()+1} — kosong`}/>;
              }
              const grade = gradeFor(pct);
              return (
                <div key={di} className={`ninety-cell ${isToday ? 'is-today' : ''}`}
                  style={{ background: gradeColor(grade), opacity: 0.3 + pct * 0.7 }}
                  title={`${d.getDate()}/${d.getMonth()+1} — ${total}/${max} (${Math.round(pct*100)}%)`}/>
              );
            })}
          </div>
        ))}
      </div>
    </div>
  );
}

function NinetyDayHero({ habits, checks, today }) {
  let totalPts = 0, maxPts = 0, doneDays = 0;
  for (let i = 0; i < 90; i++) {
    const d = new Date(today); d.setDate(d.getDate() - i);
    const dc = checks[toDateKey(d)];
    const { total, max } = pointsForDay(habits, dc);
    totalPts += total; maxPts += max;
    if (max > 0 && total / max >= 0.5) doneDays++;
  }
  const pct = maxPts > 0 ? totalPts / maxPts : 0;
  const grade = gradeFor(pct);
  const streak = computeStreak(habits, checks, today, 0.5);

  return (
    <div className="ninety-hero">
      <div className="ninety-stat">
        <div className="stat-label">Hari Konsisten</div>
        <div className="stat-value">
          <span style={{ fontFamily: 'var(--font-display)' }}>{doneDays}</span>
          <span className="stat-sub">/ 90</span>
        </div>
      </div>
      <div className="ninety-stat">
        <div className="stat-label">Grade</div>
        <div className="stat-value" style={{ color: gradeColor(grade) }}>
          <span style={{ fontFamily: 'var(--font-display)' }}>{grade}</span>
          <span className="stat-sub">{Math.round(pct * 100)}%</span>
        </div>
      </div>
      <div className="ninety-stat">
        <div className="stat-label">Streak</div>
        <div className="stat-value">
          <span style={{ fontFamily: 'var(--font-display)' }}>{streak}</span>
          <span className="stat-sub">hari</span>
        </div>
      </div>
    </div>
  );
}

function HabitProgress90({ habit, checks, today }) {
  // count main habit done in last 90 days
  let doneDays = 0;
  const cells = [];
  for (let i = 89; i >= 0; i--) {
    const d = new Date(today); d.setDate(d.getDate() - i);
    const done = !!checks[toDateKey(d)]?.[habit.id];
    if (done) doneDays++;
    cells.push(done);
  }
  const pct = doneDays / 90;
  const streak = habitStreak(habit, checks, today);
  const formed = doneDays >= HABIT_FORMED_THRESHOLD;
  const remaining = Math.max(0, HABIT_FORMED_THRESHOLD - doneDays);

  let statusText, statusColor;
  if (formed) {
    statusText = '✓ Terbentuk';
    statusColor = 'var(--accent)';
  } else if (doneDays >= 60) {
    statusText = `${remaining} hari lagi`;
    statusColor = '#C99A3C';
  } else if (doneDays >= 30) {
    statusText = 'Terbangun';
    statusColor = 'var(--muted)';
  } else if (doneDays > 0) {
    statusText = 'Memulai';
    statusColor = 'var(--muted)';
  } else {
    statusText = 'Belum';
    statusColor = 'var(--muted-2)';
  }

  return (
    <div className={`habit-progress ${formed ? 'is-formed' : ''}`}>
      <div className="hp-header">
        <span className="habit-icon" style={{ fontSize: 18 }}>{habit.icon}</span>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontWeight: 500, fontSize: 14, color: 'var(--ink)' }}>{habit.group}</div>
          <div style={{ fontSize: 11, color: 'var(--muted)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
            {habit.name}
          </div>
        </div>
        <div style={{ textAlign: 'right', flexShrink: 0 }}>
          <div style={{ fontFamily: 'var(--font-display)', fontSize: 18, fontWeight: 500, color: 'var(--ink)', lineHeight: 1 }}>
            {doneDays}<span style={{ color: 'var(--muted)', fontSize: 13 }}>/90</span>
          </div>
          {streak > 1 && (
            <div style={{ fontSize: 10, color: 'var(--accent)', marginTop: 2 }}>🔥 {streak} hari</div>
          )}
        </div>
      </div>
      <div className="hp-bar-wrap">
        <div className="hp-bar">
          <div className="hp-bar-fill" style={{
            width: `${pct * 100}%`,
            background: formed ? 'var(--accent)' : `color-mix(in oklab, var(--accent) ${30 + pct*70}%, var(--surface-2))`,
          }}/>
          {/* 80-day threshold marker */}
          <div className="hp-threshold" style={{ left: `${HABIT_FORMED_THRESHOLD/90*100}%` }}/>
        </div>
        <div className="hp-status" style={{ color: statusColor }}>{statusText}</div>
      </div>
    </div>
  );
}

function MonthNav({ month, onChange }) {
  const today = new Date();
  const isFuture = month.getFullYear() > today.getFullYear() ||
    (month.getFullYear() === today.getFullYear() && month.getMonth() >= today.getMonth());
  const go = (delta) => {
    const d = new Date(month.getFullYear(), month.getMonth() + delta, 1);
    onChange(d);
  };
  return (
    <div className="date-nav" style={{ padding: '4px 0 12px' }}>
      <button className="icon-btn" onClick={() => go(-1)} aria-label="bulan sebelumnya">
        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="15 18 9 12 15 6"/></svg>
      </button>
      <div className="date-label" style={{ pointerEvents: 'none' }}>
        <div style={{ fontFamily: 'var(--font-display)', fontSize: 18, fontWeight: 500, color: 'var(--ink)' }}>
          {formatMonth(month)}
        </div>
      </div>
      <button className="icon-btn" onClick={() => go(1)} disabled={isFuture} aria-label="bulan berikutnya"
        style={{ opacity: isFuture ? 0.3 : 1 }}>
        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="9 18 15 12 9 6"/></svg>
      </button>
    </div>
  );
}

function HeatmapCalendar({ month, habits, checks, selectedKey, onSelect }) {
  const y = month.getFullYear();
  const m = month.getMonth();
  const daysCount = daysInMonth(y, m);
  const firstDay = new Date(y, m, 1).getDay();
  const offset = (firstDay + 6) % 7;
  const cells = [];
  for (let i = 0; i < offset; i++) cells.push(null);
  for (let d = 1; d <= daysCount; d++) cells.push(d);
  while (cells.length % 7 !== 0) cells.push(null);

  const today = new Date();
  return (
    <div className="heatmap">
      <div className="heatmap-dow">
        {['Sn','Sl','Rb','Km','Jm','Sb','Mg'].map((d, i) => (
          <div key={i} style={{ color: 'var(--muted)', fontSize: 11, textAlign: 'center', fontWeight: 500, letterSpacing: '0.05em' }}>{d}</div>
        ))}
      </div>
      <div className="heatmap-grid">
        {cells.map((d, i) => {
          if (d === null) return <div key={i} />;
          const dt = new Date(y, m, d);
          const key = toDateKey(dt);
          const dc = checks[key];
          const { total, max } = pointsForDay(habits, dc);
          const pct = max > 0 ? total / max : 0;
          const isToday = isSameDay(dt, today);
          const isFuture = dt > today;
          const isSelected = key === selectedKey;
          const grade = pct > 0 ? gradeFor(pct) : null;
          const bg = isFuture ? 'transparent'
            : pct === 0 ? 'var(--surface-2)'
            : gradeColor(grade);
          const opacity = isFuture ? 0.25 : pct === 0 ? 1 : (0.3 + pct * 0.7);
          return (
            <button key={i} className={`heat-cell ${isSelected ? 'is-selected' : ''} ${isToday ? 'is-today' : ''}`}
              onClick={() => !isFuture && onSelect(key)}
              disabled={isFuture}
              style={{
                background: bg, opacity,
                color: pct > 0.4 ? 'white' : 'var(--ink)',
              }}>
              {d}
            </button>
          );
        })}
      </div>
    </div>
  );
}

function MonthSummary({ month, habits, checks }) {
  const y = month.getFullYear();
  const m = month.getMonth();
  const daysCount = daysInMonth(y, m);
  const today = new Date();

  let totalPts = 0, maxPts = 0, bestDay = null, bestPts = 0, doneDays = 0;
  let elapsedDays = 0;
  for (let d = 1; d <= daysCount; d++) {
    const dt = new Date(y, m, d);
    if (dt > today) break;
    elapsedDays++;
    const key = toDateKey(dt);
    const dc = checks[key];
    const { total, max } = pointsForDay(habits, dc);
    totalPts += total; maxPts += max;
    if (total > bestPts) { bestPts = total; bestDay = d; }
    if (max > 0 && total / max >= 0.5) doneDays++;
  }
  const pct = maxPts > 0 ? totalPts / maxPts : 0;
  const grade = gradeFor(pct);
  return (
    <div className="stat-row">
      <div className="stat-card">
        <div className="stat-label">Total Poin</div>
        <div className="stat-value">
          <span style={{ fontFamily: 'var(--font-display)' }}>{totalPts}</span>
          <span className="stat-sub">/ {maxPts}</span>
        </div>
      </div>
      <div className="stat-card">
        <div className="stat-label">Grade</div>
        <div className="stat-value" style={{ color: gradeColor(grade) }}>
          <span style={{ fontFamily: 'var(--font-display)' }}>{grade}</span>
          <span className="stat-sub">{Math.round(pct * 100)}%</span>
        </div>
      </div>
      <div className="stat-card">
        <div className="stat-label">Hari Konsisten</div>
        <div className="stat-value">
          <span style={{ fontFamily: 'var(--font-display)' }}>{doneDays}</span>
          <span className="stat-sub">/ {elapsedDays}</span>
        </div>
      </div>
      <div className="stat-card">
        <div className="stat-label">Hari Terbaik</div>
        <div className="stat-value">
          <span style={{ fontFamily: 'var(--font-display)' }}>
            {bestDay ? `${bestDay}\u00A0${MONTHS_ID_SHORT[m]}` : '—'}
          </span>
          <span className="stat-sub">{bestPts > 0 ? `${bestPts}` : ''}</span>
        </div>
      </div>
    </div>
  );
}

function DayBreakdown({ dateKey, habits, checks, onClose }) {
  const dc = checks[dateKey] || {};
  const date = parseDateKey(dateKey);
  const { total, max } = pointsForDay(habits, dc);
  const pct = max > 0 ? total / max : 0;
  const grade = gradeFor(pct);
  return (
    <div className="sheet-backdrop" onClick={onClose}>
      <div className="sheet" onClick={(e) => e.stopPropagation()}>
        <div className="sheet-handle"/>
        <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', marginBottom: 14 }}>
          <div>
            <div style={{ fontFamily: 'var(--font-display)', fontSize: 22, fontWeight: 500, color: 'var(--ink)' }}>
              {formatDateLong(date)}
            </div>
            <div style={{ fontSize: 13, color: 'var(--muted)', marginTop: 2 }}>
              {total} dari {max} poin · {Math.round(pct * 100)}%
            </div>
          </div>
          <div style={{
            fontFamily: 'var(--font-display)', fontSize: 30, fontWeight: 500,
            color: gradeColor(grade), padding: '0 12px', borderRadius: 12,
            background: gradeColor(grade) + '24',
            display: 'flex', alignItems: 'center', height: 48,
          }}>{grade}</div>
        </div>
        <div className="sheet-list">
          {habits.map(h => {
            const mainDone = !!dc[h.id];
            const doneAddons = (h.addons || []).filter(a => dc[a.id]);
            return (
              <div key={h.id} className={`sheet-row ${mainDone ? 'is-done' : ''}`}>
                <span className="sheet-icon">{h.icon}</span>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontWeight: 500, color: 'var(--ink)', fontSize: 14 }}>{h.group}</div>
                  {doneAddons.length > 0 && (
                    <div style={{ fontSize: 11, color: 'var(--accent)', marginTop: 2 }}>
                      + {doneAddons.map(a => a.name).join(', ')}
                    </div>
                  )}
                </div>
                <div className="sheet-status">
                  {mainDone ? (
                    <span style={{ color: 'var(--accent)', fontWeight: 600 }}>✓ {h.points + doneAddons.reduce((s,a)=>s+a.points,0)}</span>
                  ) : (
                    <span style={{ color: 'var(--muted-2)' }}>—</span>
                  )}
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}

function HistoryScreen({ state }) {
  const today = new Date();
  const [month, setMonth] = React.useState(new Date(today.getFullYear(), today.getMonth(), 1));
  const [selected, setSelected] = React.useState(null);
  const [view, setView] = React.useState('90'); // '90' | 'month'

  return (
    <div className="screen-body">
      <div style={{ padding: '14px 4px 4px' }}>
        <h1 style={{ fontFamily: 'var(--font-display)', fontSize: 26, fontWeight: 500, color: 'var(--ink)', margin: '0 0 10px', letterSpacing: '-0.01em' }}>
          Riwayat
        </h1>
        <div className="seg" style={{ width: '100%' }}>
          <button className={`seg-btn ${view === '90' ? 'is-active' : ''}`} onClick={() => setView('90')}>90 Hari</button>
          <button className={`seg-btn ${view === 'month' ? 'is-active' : ''}`} onClick={() => setView('month')}>Per Bulan</button>
        </div>
      </div>

      {view === '90' && (
        <>
          <div style={{ marginTop: 14 }}>
            <NinetyDayHero habits={state.habits} checks={state.checks} today={today}/>
          </div>

          <div style={{ background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 20, padding: 16, marginTop: 12 }}>
            <div style={{ fontSize: 11, color: 'var(--muted)', letterSpacing: '0.08em', textTransform: 'uppercase', fontWeight: 600, marginBottom: 10 }}>
              Aktivitas 90 Hari
            </div>
            <NinetyDayGrid habits={state.habits} checks={state.checks} today={today}/>
          </div>

          <h2 className="section-title" style={{ marginTop: 22, marginBottom: 12, paddingLeft: 4 }}>Progress Habit</h2>
          <div style={{ fontSize: 12, color: 'var(--muted)', padding: '0 4px 12px', lineHeight: 1.5 }}>
            Habit dianggap terbentuk setelah dijalani <b>80 dari 90 hari</b> terakhir.
          </div>
          <div className="habit-list">
            {state.habits.map(h => (
              <HabitProgress90 key={h.id} habit={h} checks={state.checks} today={today}/>
            ))}
          </div>
        </>
      )}

      {view === 'month' && (
        <>
          <div style={{ marginTop: 14 }}>
            <MonthNav month={month} onChange={setMonth} />
            <MonthSummary month={month} habits={state.habits} checks={state.checks} />
          </div>
          <h2 className="section-title" style={{ marginTop: 22, marginBottom: 12, paddingLeft: 4 }}>Kalender</h2>
          <HeatmapCalendar month={month} habits={state.habits} checks={state.checks}
            selectedKey={selected} onSelect={setSelected} />
          <div className="legend">
            <span style={{ color: 'var(--muted)' }}>Tingkat penyelesaian</span>
            <div className="legend-scale">
              <span className="legend-cell" style={{ background: 'var(--surface-2)' }}/>
              {[0.3, 0.5, 0.7, 0.9].map(p => (
                <span key={p} className="legend-cell"
                  style={{ background: gradeColor(gradeFor(p)), opacity: 0.3 + p * 0.7 }}/>
              ))}
            </div>
          </div>
          <div style={{ marginTop: 18, display: 'flex', gap: 8 }}>
            <button className="btn-secondary" style={{ flex: 1 }}
              onClick={() => window.__exportPDFReport?.(month, state)}>
              📄 Cetak Laporan PDF
            </button>
          </div>
        </>
      )}

      {selected && (
        <DayBreakdown dateKey={selected} habits={state.habits} checks={state.checks} onClose={() => setSelected(null)} />
      )}
    </div>
  );
}

Object.assign(window, { HistoryScreen, HeatmapCalendar, MonthSummary, DayBreakdown, NinetyDayGrid, HabitProgress90 });
