/* global React, Card, Button, Eyebrow */
// ============================================================================
// Me — profile, the dream in his words, his brother's week (witness: effort
// only, never results side by side), notifications, sign out.
// ============================================================================
(() => {
  const { useState, useEffect } = React;
  const A = () => window.PlanAPI;
  const fmtMonth = (s) => s ? new Date(s + 'T12:00:00').toLocaleString('en-GB', { month: 'long', year: 'numeric' }) : '';

  function MeScreen({ memberDb, isAdmin, go }) {
    const who = A().me();
    const kid = who.kids.find(k => k.db_id === memberDb) || {};
    const brother = who.kids.find(k => k.db_id !== memberDb);
    const [career, setCareer] = useState(null);
    const [mine, setMine] = useState(null);
    const [his, setHis] = useState(null);
    const [push, setPush] = useState(window.PushSetup ? window.PushSetup.state() : 'unavailable');
    const [err, setErr] = useState(null);

    useEffect(() => {
      const t = A().today();
      Promise.all([A().getCareer(memberDb), A().getWeek(memberDb, t), brother ? A().getWeek(brother.db_id, t) : null])
        .then(([c, w1, w2]) => { setCareer(c); setMine(w1); setHis(w2); })
        .catch(e => setErr(e.message));
    }, [memberDb]);

    const d = career && career.dream;
    return (
      <div style={{ maxWidth: 640, margin: '0 auto', padding: '20px 16px' }}>
        {err && <Card pad={14} style={{ borderColor: 'var(--danger)', marginBottom: 12 }}>Something went wrong: {err}</Card>}

        <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 18 }}>
          <div style={{ width: 52, height: 52, borderRadius: 26, background: kid.color || 'var(--signal)', color: '#fff',
                        display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 600, fontSize: 18 }}>
            {(kid.name || '?').slice(0, 1)}
          </div>
          <div>
            <div style={{ fontSize: 22, fontWeight: 500 }}>{kid.name}</div>
            <div style={{ fontSize: 13, color: 'var(--fg-muted)' }}>{isAdmin ? 'Viewing as a parent' : 'Your page'}</div>
          </div>
        </div>

        <Card pad={16} style={{ marginBottom: 12 }}>
          <Eyebrow>The dream</Eyebrow>
          {d ? (
            <div style={{ marginTop: 8, lineHeight: 1.5 }}>
              <div style={{ fontSize: 16, fontWeight: 500 }}>{d.college}{d.class_year ? `, class of ${d.class_year}` : ''}</div>
              <div style={{ fontSize: 14, color: 'var(--fg-muted)' }}>
                {d.draft_label} {fmtMonth(d.draft_date)} → first game {fmtMonth(d.first_game_date)}{d.first_game_team ? ` with ${d.first_game_team}` : ''}
              </div>
              {d.why
                ? <div style={{ marginTop: 10, fontSize: 14 }}><strong>Why:</strong> {d.why}</div>
                : <div style={{ marginTop: 10, fontSize: 14, color: 'var(--fg-muted)' }}>Your why isn’t written yet.</div>}
            </div>
          ) : <div style={{ marginTop: 8, color: 'var(--fg-muted)' }}>Not set yet.</div>}
          <div style={{ marginTop: 12 }}><Button size="sm" kind="secondary" onClick={() => go('plan', 'career')}>Open the career view</Button></div>
        </Card>

        {mine && (
          <Card pad={16} style={{ marginBottom: 12 }}>
            <Eyebrow>Your week</Eyebrow>
            <div style={{ fontSize: 15, marginTop: 8 }}>{mine.sessionsDone} of {mine.sessionsPlanned} training sessions done · {mine.done} of {mine.total} tasks</div>
          </Card>
        )}

        {brother && his && (
          <Card pad={16} style={{ marginBottom: 12 }}>
            <Eyebrow>{brother.name}’s week</Eyebrow>
            <div style={{ fontSize: 15, marginTop: 8 }}>{his.sessionsDone} of {his.sessionsPlanned} training sessions done</div>
            <div style={{ fontSize: 12, color: 'var(--fg-muted)', marginTop: 4 }}>
              You can see each other’s effort. Results stay your own — you’re on different ladders and different clocks.
            </div>
          </Card>
        )}

        <Card pad={16} style={{ marginBottom: 12 }}>
          <Eyebrow>Notifications</Eyebrow>
          <div style={{ fontSize: 14, marginTop: 8 }}>
            {push === 'on' && 'On — you’ll get a nudge for tomorrow’s plan and when something changes.'}
            {push === 'off' && 'Off.'}
            {push === 'blocked' && 'Blocked in your browser settings.'}
            {push === 'unavailable' && 'Add the app to your home screen first (Share → Add to Home Screen), then open it from there.'}
          </div>
          {push === 'off' && window.PushSetup && (
            <div style={{ marginTop: 10 }}>
              <Button size="sm" onClick={async () => { try { await window.PushSetup.enable(); } catch (e) { setErr(e.message); } setPush(window.PushSetup.state()); }}>Turn on notifications</Button>
            </div>
          )}
        </Card>

        <Card pad={16} style={{ marginBottom: 12 }}>
          <Eyebrow>How the app works</Eyebrow>
          <div style={{ fontSize: 13, color: 'var(--fg-muted)', marginTop: 8, lineHeight: 1.55 }}>
            <strong>Today</strong> is what to do now. <strong>Plan</strong> zooms out: week, month, season, career.
            <strong> Progress</strong> shows your ladders and benchmarks. <strong>Life</strong> is where you add school tests, games and activities.
            Tomorrow’s plan is ready at 18:00 the evening before.
          </div>
        </Card>

        <div style={{ textAlign: 'center', marginTop: 20 }}>
          <Button kind="ghost" size="sm" onClick={async () => { if (confirm('Sign out?')) { await window.sb.auth.signOut(); location.hash = ''; location.reload(); } }}>Sign out</Button>
        </div>
      </div>
    );
  }

  window.MeScreen = MeScreen;
})();
