/* global React, LWDATA, CLIENT_EXTRAS */
const { useState: usePrepState } = React;

// ── Prep Brief overlay — focused 5-min-before-session view ──
function PrepBrief({ client, onClose }) {
  const { c, fonts, t } = useLW();
  const { isMobile } = useViewport();

  // Real-data adapter: when the client has a `_real` payload (from useRealClient),
  // pull session log, sphere baseline, journal, goals, and pending outbox from RTDB-backed
  // state. Otherwise fall back to the LWDATA fixtures so the demo walkthrough keeps working.
  const real = client._real || null;
  const extras = (!real && typeof CLIENT_EXTRAS !== 'undefined' && CLIENT_EXTRAS[client.id]) || {};

  // Last session: real → newest session with endedAt (skip in-progress).
  // Demo → CLIENT_EXTRAS.sessionLog[0].
  const lastSession = real
    ? (real.sessions || []).find(s => s.endedAt) || null
    : (extras.sessionLog || [])[0];
  const lastSessionDate = lastSession
    ? (lastSession.endedAt
        ? new Date(Number(lastSession.endedAt))
        : (lastSession.date ? null : null))
    : null;

  // Open follow-ups: real → pending outbox items + private notes followups.
  // Demo → lastSession.followups string array.
  const outbox = real ? (real.outbox || []) : [];
  const pendingOutbox = outbox.filter(x => !x.acceptedAt && !x.skippedAt);
  const demoFollowups = !real && lastSession ? (lastSession.followups || []) : [];

  // Shared journals: real → entries since last session or last 14 days, capped at 3.
  // Demo → CLIENT_EXTRAS.journals filtered by .shared.
  const sharedJournals = real
    ? recentSharedJournals(real.journal, lastSession ? Number(lastSession.endedAt) : null)
    : (extras.journals || []).filter(j => j.shared).slice(0, 3);

  // Goals: real → real.goals (LWGoal-shape with title/quantitative*).
  // Demo → extras.goals (with .tasks array).
  const goals = real ? (real.goals || []) : (extras.goals || []);
  const todos = real ? [] : (extras.todos || []);

  const who5 = extras.who5 || [];
  const who5Now = who5.length ? who5[who5.length - 1].score : null;
  const who5Prev = who5.length > 1 ? who5[who5.length - 2].score : null;

  // Sphere baseline:
  // Demo: client.scoresPrev pre-set.
  // Real: derive from last session.scoresAtEnd. If no session yet → no baseline (show empty state).
  const baselineScores = real
    ? (lastSession && Array.isArray(lastSession.scoresAtEnd) ? lastSession.scoresAtEnd : null)
    : (client.scoresPrev || null);
  const currentScores = client.scores || null;
  const haveDeltas = baselineScores && currentScores && Array.isArray(baselineScores) && Array.isArray(currentScores);
  const deltas = haveDeltas
    ? LWDATA.SPHERE_KEYS.map((k, i) => ({
        key: k, name: LWDATA.SPHERE_NAMES[i], color: c.spheres[k],
        cur: Number(currentScores[i] ?? 0),
        prev: Number(baselineScores[i] ?? 0),
        d: Number(currentScores[i] ?? 0) - Number(baselineScores[i] ?? 0),
      })).filter(x => !isNaN(x.d))
    : [];
  const drops = deltas.filter(x => x.d < 0).sort((a,b) => a.d - b.d).slice(0, 2);
  const gains = deltas.filter(x => x.d > 0).sort((a,b) => b.d - a.d).slice(0, 2);

  const moodMonth = client.moodMonth || [];
  const moodValid = moodMonth.filter(v => v != null);
  const moodNow = moodValid.length ? moodValid[moodValid.length - 1] : null;
  const moodAvg = moodValid.length ? (moodValid.reduce((s,v)=>s+v,0) / moodValid.length).toFixed(1) : null;

  const [notes, setNotes] = usePrepState(() => {
    try { return localStorage.getItem(`prep:${client.id}`) || ''; } catch { return ''; }
  });
  const saveNotes = (v) => {
    setNotes(v);
    try { localStorage.setItem(`prep:${client.id}`, v); } catch {}
  };

  // Close on Esc
  React.useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [onClose]);

  const next = client.nextSessionISO ? new Date(client.nextSessionISO) : null;
  const minsUntil = next ? Math.round((next - new Date()) / 60000) : null;
  let sessionLabel = t('prep.session_label_default');
  if (minsUntil != null) {
    if (minsUntil < 0) sessionLabel = t('prep.session_started_ago', { n: Math.abs(minsUntil) });
    else if (minsUntil < 60) sessionLabel = t('prep.session_in_min', { n: minsUntil });
    else if (minsUntil < 1440) sessionLabel = t('prep.session_in_hr', { n: Math.round(minsUntil/60) });
  }

  return (
    <div style={{
      position: 'fixed', inset: 0, zIndex: 1000,
      background: 'rgba(8, 6, 18, 0.55)',
      backdropFilter: 'blur(8px)',
      display: 'flex', alignItems: isMobile ? 'flex-end' : 'center', justifyContent: 'center',
      padding: isMobile ? 0 : 24,
      overflow: 'auto',
    }} onClick={onClose}>
      <div onClick={e => e.stopPropagation()} style={{
        background: c.bg, color: c.textPrimary,
        width: '100%', maxWidth: 760,
        borderRadius: isMobile ? '20px 20px 0 0' : 16,
        border: `1px solid ${c.borderSubtle}`,
        boxShadow: '0 30px 80px -20px rgba(0,0,0,0.45)',
        maxHeight: isMobile ? '92vh' : '92vh',
        overflow: 'auto',
        position: 'relative',
      }}>
        {/* Header */}
        <div style={{
          position: 'sticky', top: 0, zIndex: 2,
          padding: '20px 24px 16px',
          background: c.bg,
          borderBottom: `1px solid ${c.borderSubtle}`,
          display: 'flex', alignItems: 'flex-start', gap: 16,
        }}>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontFamily: fonts.body, fontSize: 11, fontWeight: 700, letterSpacing: '0.18em', textTransform: 'uppercase', color: c.flame, marginBottom: 6 }}>
              {t('prep.eyebrow')} · {sessionLabel}
            </div>
            <div style={{ fontFamily: fonts.display, fontSize: 26, fontWeight: 500, letterSpacing: '-0.01em', color: c.textPrimary }}>
              {client.name}
            </div>
            <div style={{ fontFamily: fonts.body, fontSize: 13, color: c.textTertiary, marginTop: 2 }}>
              {lastSessionDate ? t('prep.last_session_dt', { ago: relTime(lastSessionDate.getTime()) }) + ' · ' : (real && !lastSession ? t('prep.last_session_none') + ' · ' : '')}
              {t('prep.read_5min')}
            </div>
          </div>
          <button type="button" onClick={onClose} style={{
            border: 'none', background: 'transparent', color: c.textSecondary,
            cursor: 'pointer', padding: 6, fontSize: 22, lineHeight: 1,
          }} aria-label="Close">×</button>
        </div>

        <div style={{ padding: '20px 24px 28px', display: 'flex', flexDirection: 'column', gap: 22 }}>

          {/* TL;DR snapshot */}
          <div style={{
            display: 'grid',
            gridTemplateColumns: isMobile ? 'repeat(2, 1fr)' : 'repeat(4, 1fr)',
            gap: 10,
          }}>
            {(() => {
              const scoresValid = (client.scores || []).filter(s => typeof s === 'number');
              const wheelAvg = scoresValid.length
                ? (scoresValid.reduce((s, v) => s + v, 0) / scoresValid.length).toFixed(1)
                : '—';
              return [
                { label: t('prep.snap_mood'),  value: moodNow != null ? Math.round(moodNow * 10) / 10 : '—', sub: moodAvg ? t('prep.snap_mood_avg', { n: moodAvg }) : '' },
                { label: t('prep.snap_who5'),  value: who5Now != null ? `${who5Now}` : '—', sub: who5Prev != null ? `was ${who5Prev}` : '' },
                { label: t('prep.snap_wheel'), value: wheelAvg, sub: '' },
                { label: t('prep.snap_quiet'), value: client.quietDays != null ? t('prep.snap_quiet_d', { n: client.quietDays }) : '—', sub: '' },
              ];
            })().map((m, i) => (
              <div key={i} style={{
                padding: '12px 14px', borderRadius: 10,
                background: c.bgRecessed || hexToRgba(c.textPrimary, 0.03),
                border: `1px solid ${c.borderSubtle}`,
              }}>
                <div style={{ fontFamily: fonts.body, fontSize: 10, fontWeight: 700, letterSpacing: '0.14em', textTransform: 'uppercase', color: c.textTertiary }}>
                  {m.label}
                </div>
                <div style={{ fontFamily: fonts.display, fontSize: 22, fontWeight: 600, color: c.textPrimary, marginTop: 4, letterSpacing: '-0.02em' }}>
                  {m.value}
                </div>
                {m.sub && (
                  <div style={{ fontFamily: fonts.body, fontSize: 11, color: c.textTertiary, marginTop: 1 }}>{m.sub}</div>
                )}
              </div>
            ))}
          </div>

          {/* Sphere movers */}
          <div>
            <div style={{ fontFamily: fonts.body, fontSize: 11, fontWeight: 700, letterSpacing: '0.16em', textTransform: 'uppercase', color: c.textTertiary, marginBottom: 10 }}>
              {t('prep.movers_eyebrow')}
            </div>
            {!haveDeltas ? (
              <div style={{ fontFamily: fonts.body, fontSize: 13, color: c.textTertiary, fontStyle: 'italic' }}>
                {t('prep.movers_no_baseline')}
              </div>
            ) : drops.length === 0 && gains.length === 0 ? (
              <div style={{ fontFamily: fonts.body, fontSize: 13, color: c.textTertiary, fontStyle: 'italic' }}>
                {t('prep.movers_steady')}
              </div>
            ) : (
              <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                {drops.map(d => (
                  <div key={d.key} style={{ display: 'flex', alignItems: 'center', gap: 10, fontFamily: fonts.body, fontSize: 13 }}>
                    <SphereIcon sphere={d.key} size={14} color={d.color} />
                    <span style={{ color: c.textPrimary, fontWeight: 500 }}>{d.name}</span>
                    <span style={{ color: c.textTertiary }}>{d.prev.toFixed(1)} → {d.cur.toFixed(1)}</span>
                    <span style={{ marginLeft: 'auto', color: c.flame, fontWeight: 700 }}>{d.d.toFixed(1)}</span>
                  </div>
                ))}
                {gains.map(d => (
                  <div key={d.key} style={{ display: 'flex', alignItems: 'center', gap: 10, fontFamily: fonts.body, fontSize: 13 }}>
                    <SphereIcon sphere={d.key} size={14} color={d.color} />
                    <span style={{ color: c.textPrimary, fontWeight: 500 }}>{d.name}</span>
                    <span style={{ color: c.textTertiary }}>{d.prev.toFixed(1)} → {d.cur.toFixed(1)}</span>
                    <span style={{ marginLeft: 'auto', color: c.accent, fontWeight: 700 }}>+{d.d.toFixed(1)}</span>
                  </div>
                ))}
              </div>
            )}
          </div>

          {/* Open from last session — real: pending outbox; demo: lastSession.followups */}
          {(real ? pendingOutbox.length > 0 : lastSession) && (
            <div>
              <div style={{ fontFamily: fonts.body, fontSize: 11, fontWeight: 700, letterSpacing: '0.16em', textTransform: 'uppercase', color: c.textTertiary, marginBottom: 10 }}>
                {t('prep.followups_eyebrow')}
              </div>
              <div style={{
                padding: '14px 16px', borderRadius: 10,
                border: `1px solid ${c.borderSubtle}`,
                background: hexToRgba(c.accent, 0.04),
              }}>
                {real ? (
                  <ul style={{ margin: 0, paddingLeft: 18, fontFamily: fonts.body, fontSize: 13, color: c.textSecondary, lineHeight: 1.7 }}>
                    {pendingOutbox.slice(0, 6).map((it, i) => (
                      <li key={it.id || i}>
                        <span style={{ color: c.textPrimary }}>{it.title || it.text}</span>
                        <span style={{ color: c.textTertiary, fontSize: 11, marginLeft: 6 }}>
                          · {it.pushedAt ? t('prep.outbox_pushed') : t('prep.outbox_pending')}
                        </span>
                      </li>
                    ))}
                  </ul>
                ) : (
                  <>
                    {lastSession.summary && (
                      <div style={{ fontFamily: fonts.display, fontStyle: 'italic', fontSize: 15, color: c.textPrimary, lineHeight: 1.5, marginBottom: demoFollowups.length ? 10 : 0 }}>
                        "{lastSession.summary}"
                      </div>
                    )}
                    {demoFollowups.length > 0 && (
                      <ul style={{ margin: 0, paddingLeft: 18, fontFamily: fonts.body, fontSize: 13, color: c.textSecondary, lineHeight: 1.7 }}>
                        {demoFollowups.map((f, i) => <li key={i}>{f}</li>)}
                      </ul>
                    )}
                  </>
                )}
              </div>
            </div>
          )}

          {/* What they shared */}
          {sharedJournals.length > 0 && (
            <div>
              <div style={{ fontFamily: fonts.body, fontSize: 11, fontWeight: 700, letterSpacing: '0.16em', textTransform: 'uppercase', color: c.textTertiary, marginBottom: 10 }}>
                {t('prep.shared_eyebrow')}
              </div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                {sharedJournals.map((j, i) => {
                  const sphereColor = (j.sphere && c.spheres[j.sphere]) || c.textTertiary;
                  return (
                    <div key={i} style={{
                      paddingLeft: 12, borderLeft: `2px solid ${hexToRgba(sphereColor, 0.6)}`,
                    }}>
                      <div style={{ fontFamily: fonts.body, fontSize: 11, color: c.textTertiary, fontWeight: 700, letterSpacing: '0.14em', textTransform: 'uppercase', marginBottom: 4 }}>
                        {j.ts}
                        {j.mood != null && typeof j.mood === 'number' && (
                          <span style={{ color: c.textSecondary, marginLeft: 6 }}>· mood {j.mood}/10</span>
                        )}
                      </div>
                      <div style={{ fontFamily: fonts.display, fontStyle: 'italic', fontSize: 14, color: c.textPrimary, lineHeight: 1.55, textWrap: 'pretty' }}>
                        "{j.text}"
                      </div>
                    </div>
                  );
                })}
              </div>
            </div>
          )}

          {/* Goals progress — demo only for now (real LWGoal shape doesn't expose a tasks[] array) */}
          {!real && goals.length > 0 && (
            <div>
              <div style={{ fontFamily: fonts.body, fontSize: 11, fontWeight: 700, letterSpacing: '0.16em', textTransform: 'uppercase', color: c.textTertiary, marginBottom: 10 }}>
                Goals progress
              </div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                {goals.map(g => {
                  const done = g.tasks.filter(t => t.done).length;
                  const pct = g.tasks.length ? done / g.tasks.length : 0;
                  const color = c.spheres[g.sphere] || c.accent;
                  return (
                    <div key={g.id} style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                      <SphereIcon sphere={g.sphere} size={14} color={color} />
                      <div style={{ flex: 1, fontFamily: fonts.body, fontSize: 13, color: c.textPrimary, fontWeight: 500 }}>
                        {g.title}
                      </div>
                      <div style={{ width: 100, height: 4, borderRadius: 2, background: c.borderSubtle, overflow: 'hidden' }}>
                        <div style={{ width: `${pct*100}%`, height: '100%', background: color }} />
                      </div>
                      <div style={{ fontFamily: fonts.app, fontSize: 12, fontWeight: 700, color: c.textSecondary, minWidth: 32, textAlign: 'right' }}>
                        {done}/{g.tasks.length}
                      </div>
                    </div>
                  );
                })}
              </div>
            </div>
          )}

          {/* Coach notes */}
          <div>
            <div style={{ fontFamily: fonts.body, fontSize: 11, fontWeight: 700, letterSpacing: '0.16em', textTransform: 'uppercase', color: c.textTertiary, marginBottom: 8 }}>
              {t('prep.notes_eyebrow')}
            </div>
            <textarea
              value={notes}
              onChange={(e) => saveNotes(e.target.value)}
              placeholder={t('prep.notes_placeholder', { name: client.name.split(' ')[0] })}
              style={{
                width: '100%', minHeight: 90, padding: 12,
                fontFamily: fonts.body, fontSize: 14, lineHeight: 1.5,
                color: c.textPrimary, background: c.bgRecessed || hexToRgba(c.textPrimary, 0.03),
                border: `1px solid ${c.borderSubtle}`, borderRadius: 8,
                resize: 'vertical', outline: 'none', boxSizing: 'border-box',
              }}
            />
            <div style={{ marginTop: 4, fontFamily: fonts.body, fontSize: 11, color: c.textTertiary, fontStyle: 'italic' }}>
              {t('prep.notes_hint')}
            </div>
          </div>
        </div>

        {/* Footer actions */}
        <div style={{
          position: 'sticky', bottom: 0,
          padding: '14px 24px',
          background: c.bg,
          borderTop: `1px solid ${c.borderSubtle}`,
          display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap',
        }}>
          <a href={client.userUid
              ? `Session.html?clientId=${encodeURIComponent(client.userUid)}`
              : `Session.html?id=next-${client?.id || ''}`}
             style={{ textDecoration: 'none' }}>
            <Button variant="primary" size="md" icon={<span aria-hidden style={{ fontSize: 12 }}>▸</span>}>
              {t('prep.start_session')}
            </Button>
          </a>
          <Button variant="ghost" size="md" onClick={onClose}>
            {t('prep.see_full')}
          </Button>
          <span style={{ flex: 1 }} />
          <span style={{ fontFamily: fonts.body, fontSize: 11, color: c.textTertiary }}>{t('prep.esc_to_close')}</span>
        </div>
      </div>
    </div>
  );
}

// Pull recent shared journals from real-mode list. Filters to entries created
// after the last session ended (or in last 14 days if no session yet) and caps
// to 3. Prefers entries with body content over title-only.
function recentSharedJournals(journal, sinceMs) {
  if (!journal || journal.length === 0) return [];
  const cutoff = sinceMs && !isNaN(sinceMs)
    ? sinceMs
    : Date.now() - 14 * 86_400_000;
  return journal
    .filter(j => j && j.body && (j.body || '').trim())
    .map(j => {
      const t = Number(j.creationDate) || 0;
      // RTDB stores creationDate as Unix seconds (fractional). Promote to ms if needed.
      const ts = t > 1e12 ? t : t * 1000;
      return {
        ts,
        text: j.body,
        sphere: j.sphere || null,
        mood: j.moodEmoji || null,
      };
    })
    .filter(j => j.ts >= cutoff)
    .sort((a, b) => b.ts - a.ts)
    .slice(0, 3)
    .map(j => ({
      ts: relTime(j.ts),
      text: j.text,
      sphere: j.sphere,
      mood: j.mood,
    }));
}
function relTime(ms) {
  const diff = Date.now() - ms;
  const t = (window.LWLang && window.LWLang.t) ? window.LWLang.t : ((k) => k);
  if (diff < 60_000) return t('prep.rel_just_now');
  if (diff < 3_600_000) return t('prep.rel_min_ago', { n: Math.round(diff / 60_000) });
  if (diff < 86_400_000) return t('prep.rel_hr_ago', { n: Math.round(diff / 3_600_000) });
  return t('prep.rel_day_ago', { n: Math.round(diff / 86_400_000) });
}

window.PrepBrief = PrepBrief;
