// ─────────────────────────────────────────────────────────────
// LifeWheel Coach — Marathon (cohort host) view.
// Renders aggregates + per-participant table for the expert hosting
// the cohort. Calls cloud function `cohortParticipants` which performs
// the role/expertId verification + privileged read across /users.
// ─────────────────────────────────────────────────────────────

function LWMarathon() {
  const [loading, setLoading] = React.useState(true);
  const [error, setError] = React.useState(null);
  const [cohorts, setCohorts] = React.useState([]);   // list { id, expertName, potokNumber, durationDays }
  const [activeId, setActiveId] = React.useState(null);
  const [data, setData] = React.useState(null);       // result of cohortParticipants

  // 1) On mount: figure out which cohorts this user can host.
  React.useEffect(() => {
    (async () => {
      try {
        const auth = window.LWFB.auth.currentUser;
        if (!auth) { setError('not_signed_in'); setLoading(false); return; }

        const expertSnap = await window.LWFB.db.ref(`/users/${auth.uid}/expertId`).get();
        const expertId = expertSnap.exists() ? String(expertSnap.val() || '') : '';
        if (!expertId) {
          setError('no_expert');
          setLoading(false);
          return;
        }

        // List all cohorts and filter client-side (small dataset).
        const allSnap = await window.LWFB.db.ref('/cohorts').get();
        const matching = [];
        allSnap.forEach(child => {
          const c = child.val() || {};
          if (c.expertId === expertId) {
            matching.push({
              id: child.key,
              expertId: c.expertId,
              potokNumber: c.potokNumber || 0,
              durationDays: c.durationDays || 5,
              startsAt: c.startsAt || 0,
            });
          }
        });

        if (!matching.length) { setError('no_cohorts'); setLoading(false); return; }
        // Most recent first
        matching.sort((a, b) => (b.startsAt || 0) - (a.startsAt || 0));
        setCohorts(matching);
        setActiveId(matching[0].id);
      } catch (e) {
        console.error('[marathon] init', e);
        setError(String(e && e.message || e));
        setLoading(false);
      }
    })();
  }, []);

  // 2) Load participants for the active cohort.
  React.useEffect(() => {
    if (!activeId) return;
    setLoading(true);
    setData(null);
    setError(null);

    (async () => {
      try {
        if (!firebase.functions) {
          setError('functions_sdk_missing');
          setLoading(false);
          return;
        }
        const fn = firebase.functions().httpsCallable('cohortParticipants');
        const res = await fn({ cohortId: activeId });
        setData(res.data || null);
      } catch (e) {
        console.error('[marathon] fetch', e);
        setError(String(e && e.message || e));
      } finally {
        setLoading(false);
      }
    })();
  }, [activeId]);

  if (loading && !data) {
    return (
      <div style={S.shell}>
        <div style={S.muted}>Загрузка участников…</div>
      </div>
    );
  }

  if (error === 'no_expert') {
    return (
      <div style={S.shell}>
        <h1 style={S.h1}>Марафон-портал</h1>
        <div style={S.card}>
          <div style={S.muted}>Этот аккаунт не зарегистрирован как ведущий марафона. Свяжитесь с командой LifeWheel.</div>
        </div>
      </div>
    );
  }
  if (error === 'no_cohorts') {
    return (
      <div style={S.shell}>
        <h1 style={S.h1}>Марафон-портал</h1>
        <div style={S.card}>
          <div style={S.muted}>Активных марафонов пока нет.</div>
        </div>
      </div>
    );
  }
  if (error) {
    return (
      <div style={S.shell}>
        <h1 style={S.h1}>Марафон-портал</h1>
        <div style={S.card}>
          <div style={{ ...S.muted, color: '#E85D5D' }}>Ошибка: {error}</div>
        </div>
      </div>
    );
  }

  return (
    <div style={S.shell}>
      <header style={S.header}>
        <h1 style={S.h1}>Марафон-портал</h1>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          {cohorts.length > 1 && (
            <select value={activeId || ''} onChange={e => setActiveId(e.target.value)} style={S.select}>
              {cohorts.map(c => (
                <option key={c.id} value={c.id}>Поток #{c.potokNumber} — {c.id}</option>
              ))}
            </select>
          )}
          <a href="#/cms" style={{ ...S.select, textDecoration: 'none', color: '#3EC08D', borderColor: 'rgba(62,192,141,0.35)' }}>
            ✎ Редактировать контент
          </a>
        </div>
      </header>

      {data && <AggregateStrip aggregates={data.aggregates} cohort={data.cohort} />}
      {data && <DayProgressGrid aggregates={data.aggregates} durationDays={data.cohort.durationDays} />}
      {data && <ParticipantTable participants={data.participants} durationDays={data.cohort.durationDays} />}
    </div>
  );
}

function AggregateStrip({ aggregates, cohort }) {
  const a = aggregates || {};
  const cells = [
    { label: 'всего', value: a.total ?? 0 },
    { label: 'не закончили онбординг', value: a.onboardingIncomplete ?? 0 },
    { label: 'дошли до Точки Б', value: a.tochkaBComplete ?? 0 },
    { label: 'истекло', value: a.expired ?? 0 },
  ];
  return (
    <div style={S.aggGrid}>
      {cells.map(c => (
        <div key={c.label} style={S.aggCell}>
          <div style={S.aggValue}>{c.value}</div>
          <div style={S.aggLabel}>{c.label}</div>
        </div>
      ))}
    </div>
  );
}

function DayProgressGrid({ aggregates, durationDays }) {
  const a = aggregates || {};
  const days = [];
  for (let d = 1; d <= durationDays; d++) days.push(d);
  return (
    <div style={S.card}>
      <div style={S.cardTitle}>По дням</div>
      <div style={S.dayGrid}>
        {days.map(d => (
          <div key={d} style={S.dayCell}>
            <div style={S.dayN}>День {d}</div>
            <div style={S.dayMetric}>
              <span style={S.dayMetricBig}>{(a.completedDayCounts || {})[d] || 0}</span>
              <span style={S.dayMetricLabel}>выполнено</span>
            </div>
            <div style={S.dayMetric}>
              <span style={S.dayMetricBig}>{(a.byCurrentDay || {})[d] || 0}</span>
              <span style={S.dayMetricLabel}>сейчас здесь</span>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

function ParticipantTable({ participants, durationDays }) {
  const list = participants || [];
  if (!list.length) {
    return (
      <div style={S.card}>
        <div style={S.muted}>Пока никто не присоединился.</div>
      </div>
    );
  }
  return (
    <div style={S.card}>
      <div style={S.cardTitle}>Участники ({list.length})</div>
      <div style={S.table}>
        <div style={{ ...S.tr, ...S.thRow }}>
          <div style={{ ...S.td, flex: 3 }}>Декларация</div>
          <div style={{ ...S.td, flex: 1, textAlign: 'center' }}>День</div>
          <div style={{ ...S.td, flex: 2, textAlign: 'center' }}>Прогресс</div>
          <div style={{ ...S.td, flex: 1, textAlign: 'right' }}>Точка Б</div>
        </div>
        {list.map(p => (
          <div key={p.uid} style={S.tr}>
            <div style={{ ...S.td, flex: 3 }}>
              {p.onboardingIncomplete
                ? <span style={S.warn}>не закончил(а) онбординг</span>
                : (p.declaration || <span style={S.muted}>—</span>)}
            </div>
            <div style={{ ...S.td, flex: 1, textAlign: 'center' }}>
              {p.onboardingIncomplete ? '—' : p.currentDay}
            </div>
            <div style={{ ...S.td, flex: 2, textAlign: 'center' }}>
              <DayDots durationDays={durationDays} completed={p.completedDays || []} />
            </div>
            <div style={{ ...S.td, flex: 1, textAlign: 'right' }}>
              {p.tochkaBComplete ? <span style={S.dot}>✓</span> : <span style={S.muted}>—</span>}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

function DayDots({ durationDays, completed }) {
  const set = new Set(completed);
  const items = [];
  for (let d = 1; d <= durationDays; d++) {
    const done = set.has(d);
    items.push(
      <span key={d} title={`День ${d}`} style={{
        display: 'inline-block', width: 10, height: 10, margin: '0 3px',
        borderRadius: 5, background: done ? '#3EC08D' : 'rgba(255,255,255,0.15)',
      }} />
    );
  }
  return <div>{items}</div>;
}

const S = {
  shell:     { padding: '32px 28px', maxWidth: 1100, margin: '0 auto', fontFamily: "'Inter', system-ui, sans-serif", color: 'rgba(255,255,255,0.92)' },
  header:    { display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 24 },
  h1:        { margin: 0, fontFamily: "'Fraunces', Georgia, serif", fontWeight: 600, fontSize: 32, letterSpacing: -0.5 },
  select:    { background: '#1A3226', color: 'rgba(255,255,255,0.92)', border: '1px solid rgba(255,255,255,0.15)', padding: '8px 12px', borderRadius: 8, fontSize: 14 },
  card:      { background: 'rgba(255,255,255,0.04)', border: '1px solid rgba(255,255,255,0.08)', borderRadius: 14, padding: 20, marginTop: 16 },
  cardTitle: { fontSize: 12, textTransform: 'uppercase', letterSpacing: 1.4, color: 'rgba(255,255,255,0.55)', marginBottom: 14 },
  muted:     { color: 'rgba(255,255,255,0.45)', fontStyle: 'italic' },
  warn:      { color: '#E8943A', fontStyle: 'italic' },
  dot:       { color: '#3EC08D', fontWeight: 700 },

  aggGrid:   { display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14, marginTop: 8 },
  aggCell:   { background: 'rgba(62,192,141,0.06)', border: '1px solid rgba(62,192,141,0.20)', borderRadius: 12, padding: '18px 16px' },
  aggValue:  { fontFamily: "'Fraunces', Georgia, serif", fontSize: 32, fontWeight: 600, color: '#3EC08D' },
  aggLabel:  { marginTop: 4, fontSize: 12, color: 'rgba(255,255,255,0.65)', textTransform: 'lowercase' },

  dayGrid:        { display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(140px, 1fr))', gap: 12 },
  dayCell:        { background: 'rgba(255,255,255,0.03)', borderRadius: 10, padding: 14 },
  dayN:           { fontSize: 13, fontWeight: 600, color: 'rgba(255,255,255,0.75)', marginBottom: 8 },
  dayMetric:      { display: 'flex', alignItems: 'baseline', gap: 6, marginBottom: 4 },
  dayMetricBig:   { fontFamily: "'Fraunces', Georgia, serif", fontSize: 22, color: 'rgba(255,255,255,0.95)' },
  dayMetricLabel: { fontSize: 11, color: 'rgba(255,255,255,0.50)' },

  table:     { display: 'flex', flexDirection: 'column' },
  tr:        { display: 'flex', alignItems: 'center', padding: '10px 6px', borderBottom: '1px solid rgba(255,255,255,0.06)' },
  thRow:     { fontSize: 11, textTransform: 'uppercase', letterSpacing: 1.2, color: 'rgba(255,255,255,0.55)' },
  td:        { padding: '0 8px', fontSize: 14 },
};

window.LWMarathon = LWMarathon;
