// whats-new.jsx — Release notes + near-term roadmap surface.
//
// Edit CHANGES below to publish a new entry. Newest first.
// Each entry's `id` is what's stored in localStorage to track "read" state;
// never reuse an id. Use ISO date for `date`.
//
// `type` controls the chip color: 'feature' | 'update' | 'fix' | 'note'.
// Roadmap entries are listed separately in ROADMAP below — they don't count
// toward the unread badge.

const CHANGES = [
  {
    id: '2026-05-20-whats-new',
    date: '2026-05-20',
    type: 'feature',
    title: 'What\'s New page',
    summary: 'See recent updates and what we\'re building next in one place.',
    body: 'Every time the dashboard ships a change, you\'ll see it here. The bell on the sidebar lights up when there\'s something new. Tap "Roadmap" at the bottom to see what we\'re working on next.',
  },
  {
    id: '2026-05-20-aa-to-olie',
    date: '2026-05-20',
    type: 'update',
    title: 'A&A metrics + rock now assigned to Olie',
    summary: 'Until the Community Liaison seat is filled, all four A&A metrics and the A&A Campaign rock sit with Olie.',
    body: 'Once a new Liaison is hired, Olie will be able to reassign these from the Metrics Map. Affected metrics: Leads, Partner outreach, Partner meetings, Webinars. Affected rock: A&A Campaign LIVE.',
  },
  {
    id: '2026-05-18-rolling-13',
    date: '2026-05-18',
    type: 'update',
    title: '13-Week Scorecard now rolls forward',
    summary: 'The Scorecard always shows the most recent 13 weeks ending on the current Thursday — no empty future cells.',
    body: 'Column headers are week-ending Thursdays. Today\'s column is the rightmost one. As each Thursday closes, the oldest column drops off and a fresh one appears on the right.',
  },
  {
    id: '2026-05-01-training-tour',
    date: '2026-05-01',
    type: 'feature',
    title: 'Training view + welcome tour',
    summary: 'First-login walkthrough plus a Training tab with the full team SOP.',
    body: 'New teammates get a 4-step tour the first time they sign in. The Training tab keeps the full team-training SOP available any time — replay the tour from there if you want a refresher.',
  },
  {
    id: '2026-04-29-feedback',
    date: '2026-04-29',
    type: 'feature',
    title: 'In-app feedback button',
    summary: 'Send Dave + Olie feedback without leaving the dashboard.',
    body: 'Tap "Send feedback" in the sidebar to flag anything that feels off, broken, or missing. Dave and Olie see them in the Feedback tab.',
  },
];

const ROADMAP = [
  {
    id: 'roadmap-rock-crud',
    title: 'Full rock management for Olie',
    body: 'Olie will be able to add new rocks, edit titles and due dates, reassign owners, and delete rocks that no longer apply. Rock % updates will also save to the database (right now the slider only saves locally).',
    when: 'Next',
  },
  {
    id: 'roadmap-scorecard-periods',
    title: 'Scorecard view selector — Q1 / Q2 / Q3 / Trailing 13',
    body: 'When Q3 starts, your Q2 data won\'t vanish. A dropdown at the top of the Scorecard will let anyone view any prior quarter or the rolling 13 weeks.',
    when: 'Before Q3 (by 6/30)',
  },
  {
    id: 'roadmap-push',
    title: 'Push notifications',
    body: 'Daily reminder at 7 AM if you haven\'t entered your numbers yet. Email fallback at 8 PM if the day\'s still missing.',
    when: 'Soon',
  },
  {
    id: 'roadmap-import',
    title: 'CSV import',
    body: 'Bulk import historical entries from spreadsheets — useful for catching up past data or for a new hire backfilling their week.',
    when: 'Soon',
  },
  {
    id: 'roadmap-ai-coach',
    title: 'AI Coach (live)',
    body: 'Claude-powered analysis of your scorecard trends with suggested actions. Already roughed in; needs to be connected to live data before launch.',
    when: 'Later',
  },
];

// ──────────────────────────────── unread state ────────────────────────────
const WHATS_NEW_READ_KEY = 'norwill-whatsnew-read-v1';

function readLog() {
  try { return JSON.parse(localStorage.getItem(WHATS_NEW_READ_KEY) || '{}'); }
  catch { return {}; }
}

function readIdsForUid(uid) {
  if (!uid) return new Set();
  const log = readLog();
  return new Set(log[uid] || []);
}

function markAllRead(uid) {
  if (!uid) return;
  try {
    const log = readLog();
    log[uid] = CHANGES.map(c => c.id);
    localStorage.setItem(WHATS_NEW_READ_KEY, JSON.stringify(log));
  } catch {}
}

function unreadCountForUid(uid) {
  if (!uid) return 0;
  const seen = readIdsForUid(uid);
  return CHANGES.filter(c => !seen.has(c.id)).length;
}

// ──────────────────────────────── chip styling ────────────────────────────
const TYPE_META = {
  feature: { label: 'New',     bg: 'var(--forest-mist)', color: 'var(--norwill-forest)' },
  update:  { label: 'Updated', bg: 'rgba(180, 130, 60, 0.10)', color: 'var(--amber-deep)' },
  fix:     { label: 'Fixed',   bg: 'rgba(94, 137, 63, 0.12)',  color: 'var(--summit)' },
  note:    { label: 'Note',    bg: 'var(--surface-sunk)',      color: 'var(--ink-700)' },
};

function fmtDate(iso) {
  if (!iso) return '';
  const d = new Date(iso + 'T00:00:00');
  if (isNaN(d.getTime())) return iso;
  return d.toLocaleDateString('en-US', { month: 'long', day: 'numeric', year: 'numeric' });
}

// ──────────────────────────────── view ────────────────────────────────────
function WhatsNew({ authUser }) {
  const uid = authUser?.uid || authUser?.username || null;
  const [seen, setSeen] = React.useState(() => readIdsForUid(uid));

  // Mark every entry read as soon as the view opens, then update the badge.
  React.useEffect(() => {
    if (!uid) return;
    markAllRead(uid);
    setSeen(new Set(CHANGES.map(c => c.id)));
    window.dispatchEvent(new CustomEvent('norwill:whatsnew-read'));
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [uid]);

  return (
    <div style={{ padding: 'clamp(20px, 3vw, 32px)', maxWidth: 880 }}>
      <div className="view-header" style={{ flexWrap: 'wrap' }}>
        <div>
          <div className="eyebrow">Release notes</div>
          <h2 className="view-title">What's New</h2>
          <div className="view-sub">
            Recent updates to the dashboard and what we're working on next.
          </div>
        </div>
      </div>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 14, marginTop: 8 }}>
        {CHANGES.map(entry => {
          const meta = TYPE_META[entry.type] || TYPE_META.note;
          const isNew = !seen.has(entry.id);
          return (
            <article key={entry.id} className="card" style={{
              padding: '18px 20px',
              display: 'flex', flexDirection: 'column', gap: 8,
              borderLeft: isNew ? '3px solid var(--norwill-forest)' : '3px solid transparent',
            }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap' }}>
                <span style={{
                  display: 'inline-flex', alignItems: 'center',
                  background: meta.bg, color: meta.color,
                  padding: '3px 9px', borderRadius: 99,
                  fontSize: 11, fontWeight: 700, letterSpacing: 0.04,
                  textTransform: 'uppercase',
                }}>{meta.label}</span>
                <span style={{ fontSize: 12, color: 'var(--ink-500)' }}>{fmtDate(entry.date)}</span>
              </div>
              <h3 style={{
                margin: 0,
                fontFamily: 'var(--font-display)', fontWeight: 600,
                fontSize: 19, lineHeight: 1.25,
                color: 'var(--ink-900)', letterSpacing: '-0.01em',
              }}>{entry.title}</h3>
              <p style={{ margin: 0, color: 'var(--ink-700)', fontSize: 14.5, lineHeight: 1.55 }}>
                {entry.summary}
              </p>
              {entry.body && (
                <p style={{ margin: 0, color: 'var(--ink-600)', fontSize: 13.5, lineHeight: 1.55 }}>
                  {entry.body}
                </p>
              )}
            </article>
          );
        })}
      </div>

      <div style={{ marginTop: 36 }}>
        <div className="eyebrow">Roadmap</div>
        <h3 style={{
          margin: '4px 0 4px',
          fontFamily: 'var(--font-display)', fontWeight: 500,
          fontSize: 22, letterSpacing: '-0.01em', color: 'var(--ink-900)',
        }}>What's coming next</h3>
        <div style={{ color: 'var(--ink-600)', fontSize: 13.5, marginBottom: 14 }}>
          In active development. Timelines are estimates — we'll post here when each one ships.
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {ROADMAP.map(item => (
            <div key={item.id} style={{
              padding: '14px 18px',
              border: '1px solid var(--hairline)',
              borderRadius: 12,
              background: 'var(--surface-card)',
            }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap', marginBottom: 4 }}>
                <span style={{
                  display: 'inline-flex', alignItems: 'center',
                  background: 'var(--surface-sunk)', color: 'var(--ink-700)',
                  padding: '2px 8px', borderRadius: 99,
                  fontSize: 10.5, fontWeight: 700, letterSpacing: 0.06,
                  textTransform: 'uppercase',
                }}>{item.when}</span>
              </div>
              <div style={{
                fontFamily: 'var(--font-display)', fontWeight: 500,
                fontSize: 16, color: 'var(--ink-900)', marginBottom: 4,
              }}>{item.title}</div>
              <div style={{ color: 'var(--ink-600)', fontSize: 13.5, lineHeight: 1.55 }}>
                {item.body}
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { WhatsNew, unreadCountForUid });
