const TABS = [{ id: 'home', label: 'Home', icon: 'home' }, { id: 'profile', label: 'Profile', icon: 'person' }];

function Home({ s, onTab, onPlay, onRide, onEditGoals, onScience, onPro }) {
  const { PhoneShell, OptionChip, Button, ActivityRings, ListGroup, ListRow, TabBar, Icon } = window.GG;
  const { DRILLS, DRILL_ORDER, PRIORITIES, avatar } = window.GGData;
  const name = s.firstName.trim() || 'Feargal';
  const done = s.completedDrills;
  const lr = s.lastRide;
  const W = window.WORLDS || {}; const w = W[s.world] || W.space;
  const focus = (s.selectedPriorities.length ? s.selectedPriorities : ['focus', 'memory', 'speed']).map(id => PRIORITIES.find(p => p.id === id));
  return (
    <PhoneShell>
      <Screen tabBar={<TabBar items={TABS} active="home" onSelect={onTab} />}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '10px 0 0' }}>
          <button type="button" onClick={() => onTab('profile')} style={{ width: 48, height: 48, borderRadius: '50%', padding: 0, border: '2px solid var(--gg-cyan)', boxShadow: '0 0 14px color-mix(in srgb, var(--gg-cyan) 40%, transparent)', overflow: 'hidden', cursor: 'pointer', flex: 'none', background: '#222' }}>
            <img src={avatar(s.calibration.gender)} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} />
          </button>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 22, fontWeight: 800, letterSpacing: '-0.02em', lineHeight: 1.15 }}>Hi, {name}!</div>
            <div style={{ fontSize: 12, fontWeight: 600, color: 'var(--text-muted)', marginTop: 2, whiteSpace: 'nowrap' }}><span style={{ color: 'var(--gg-cyan)', fontWeight: 800 }}>1-day streak</span> · {done.length}/3 drills{done.length >= 3 && !s.isPro ? <> · <span role="button" onClick={onPro} style={{ color: 'var(--gg-domain-memory)', fontWeight: 800, cursor: 'pointer' }}>Upgrade for more</span></> : null}</div>
          </div>
        </div>


        <div style={{ marginTop: 20, borderRadius: 'var(--radius-panel)', overflow: 'hidden', position: 'relative', border: '1px solid color-mix(in srgb, var(--gg-cyan) 35%, transparent)', boxShadow: '0 0 30px color-mix(in srgb, var(--gg-cyan) 18%, transparent)' }}>
          <div style={{ position: 'absolute', left: 0, right: 0, top: 0, aspectRatio: '712 / 255', background: 'url(' + ((window.__resources && window.__resources['hero']) || '../../assets/hero-spin-bike.png') + ') center top/100% auto no-repeat' }}></div>
          <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(180deg, transparent 0%, transparent 18%, rgba(7,7,10,0.72) 38%, #0c0e14 58%)' }}></div>
          <div style={{ position: 'relative', padding: '120px 20px 20px' }}>
            <div style={{ display: 'flex', alignItems: 'flex-end', gap: 16 }}>
              <div style={{ flex: 1, minWidth: 0 }}>
                <Meta color="var(--gg-cyan)">Today's Brain Ride</Meta>
                <div style={{ fontSize: 28, fontWeight: 800, letterSpacing: '-0.025em', lineHeight: 1.06, marginTop: 4 }}>{w.name}</div>
                <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--text-muted)', marginTop: 6 }}>{window.burstCount(w)} Brain Bursts + Sprint · ~{Math.max(1, Math.round(window.rideLen(w, true) / 60))} min</div>
              </div>
              <ActivityRings size={84} rings={[{ value: lr ? lr.acc / 100 : 0.02, color: 'var(--gg-cyan)' }, { value: lr ? Math.min(1, lr.best / 5) : 0.02, color: 'var(--gg-domain-memory)' }, { value: lr ? lr.sAcc / 100 : 0.02, color: 'var(--gg-domain-speed)' }]} />
            </div>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 10, marginTop: 12 }}>
              {focus.map(p => <span key={p.id} style={{ fontSize: 11, fontWeight: 800, letterSpacing: '0.05em', textTransform: 'uppercase', color: `var(--gg-domain-${p.id})` }}>{p.kicker}</span>)}
            </div>
            <div style={{ marginTop: 16 }}><Button icon={w.icon} onClick={onRide}>Start {w.name}</Button></div>
          </div>
        </div>
        <div style={{ display: 'flex', gap: 16, marginTop: 10, padding: '0 4px' }}>
          {[[lr ? 'Accuracy ' + lr.acc + '%' : 'Accuracy', 'var(--gg-cyan)'], [lr ? 'Longest streak ' + lr.best : 'Longest streak', 'var(--gg-domain-memory)'], [lr ? 'Sprint ' + lr.sAcc + '%' : 'Sprint accuracy', 'var(--gg-domain-speed)']].map(([l, c]) => <span key={l} style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 11, fontWeight: 700, color: 'var(--text-muted)' }}><span style={{ width: 8, height: 8, borderRadius: '50%', background: c }}></span>{l}</span>)}
        </div>

        <Section label="Quick drills" right={<QuietLink color="var(--gg-cyan)" onClick={onEditGoals}>Edit goals</QuietLink>}>
          <ListGroup>
            {DRILL_ORDER.map(id => { const d = DRILLS[id]; const ok = done.includes(id); return (
              <ListRow key={id} icon={d.icon} color={d.color} title={`${d.order}. ${d.title}`} subtitle={d.durationLabel} onClick={() => onPlay(id)}
                trailing={ok ? <span style={{ display: 'flex', alignItems: 'center', gap: 4, fontSize: 12, fontWeight: 800, color: 'var(--gg-domain-composure)' }}><Icon name="check_circle" size={18} fill />Done</span> : <span style={{ fontSize: 13, fontWeight: 800, color: d.color }}>Play</span>} />); })}
          </ListGroup>
        </Section>

        <div style={{ marginTop: 16 }}>
          {!s.isPro ? (
            <ListGroup><ListRow icon="workspace_premium" color="var(--gg-domain-memory)" title="Genius Pro" subtitle="$19.99/month or $199/year · Unlimited rides" onClick={onPro} trailing={<Chevron />} /></ListGroup>
          ) : (
            <ListGroup><ListRow icon="workspace_premium" color="var(--gg-domain-memory)" title="Genius Pro active" subtitle="Unlimited rides · WhatsApp · Founder call" trailing={<Meta color="var(--gg-domain-memory)">Active</Meta>} /></ListGroup>
          )}
        </div>
      </Screen>
    </PhoneShell>
  );
}

function Profile({ s, set, onTab, onTogglePriority, onPro, onLogout }) {
  const { PhoneShell, ListGroup, ListRow, Toggle, OptionChip, Button, TabBar, Icon, Segmented } = window.GG;
  const { PRIORITIES, DURATIONS, GENDERS, avatar, tone } = window.GGData;
  const [open, setOpen] = React.useState(null);
  const tog = k => { tone(450); setOpen(o => (o === k ? null : k)); };
  const cal = s.calibration;
  const Edit = ({ k }) => <span style={{ fontSize: 13, fontWeight: 800, color: 'var(--gg-cyan)' }}>{open === k ? 'Done' : 'Edit'}</span>;
  const pad = { padding: '4px 16px 16px', display: 'flex', flexDirection: 'column', gap: 12 };
  return (
    <PhoneShell>
      <Screen tabBar={<TabBar items={TABS} active="profile" onSelect={onTab} />}>
        <TopBar center={<span style={{ fontSize: 15, fontWeight: 800 }}>Profile &amp; Settings</span>} right={<QuietLink color="var(--gg-cyan)" onClick={() => onTab('home')}>Done</QuietLink>} />
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', textAlign: 'center', marginTop: 12 }}>
          <div style={{ width: 88, height: 88, borderRadius: '50%', overflow: 'hidden', border: '3px solid var(--gg-cyan)', boxShadow: '0 0 24px color-mix(in srgb, var(--gg-cyan) 40%, transparent)' }}><img src={avatar(cal.gender)} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} /></div>
          <div style={{ fontSize: 22, fontWeight: 800, marginTop: 12 }}>{s.firstName.trim() || 'Genius Member'}</div>
          <div style={{ fontSize: 13, color: 'var(--text-muted)', marginTop: 2 }}>{s.email.trim() || 'No email set'}</div>
          <div style={{ marginTop: 8 }}><Meta color={s.isPro ? 'var(--gg-domain-memory)' : 'var(--gg-cyan)'}>{s.isPro ? 'Genius Pro member' : 'Free starter plan'}</Meta></div>
        </div>
        {!s.isPro && <div style={{ marginTop: 20 }}><ListGroup><ListRow icon="workspace_premium" color="var(--gg-domain-memory)" title="Upgrade to Genius Pro" subtitle="$19.99/month or $199/year · Unlimited rides" onClick={onPro} trailing={<Chevron />} /></ListGroup></div>}
        <div style={{ marginTop: 24 }}>
          <ListGroup label="Riding comfort">
            <ListRow icon="format_size" title="Large text" subtitle="Bigger cues, labels and rules" trailing={<Toggle checked={!!s.largeText} onChange={v => set({ largeText: v })} label="Large text" />} />
            <ListRow icon="contrast" color="#ffffff" title="High-contrast ride mode" subtitle="Pure black and white, no glow" trailing={<Toggle checked={!!s.highContrast} onChange={v => set({ highContrast: v })} label="High-contrast ride mode" />} />
            <ListRow icon="record_voice_over" color="var(--gg-domain-composure)" title="Spoken voice" trailing={<div style={{ width: 200 }}><Segmented value={s.voice === false ? 'off' : (s.speech || 'slow')} onChange={v => set(v === 'off' ? { voice: false } : { voice: true, speech: v })} options={[{ value: 'off', label: 'Off' }, { value: 'slow', label: 'Slower' }, { value: 'normal', label: 'Normal' }]} /></div>} />
            <ListRow icon="vibration" color="var(--gg-domain-memory)" title="Haptic feedback" subtitle="Buzz on taps and answers" trailing={<Toggle checked={s.haptics !== false} onChange={v => set({ haptics: v })} label="Haptic feedback" />} />
            <ListRow icon="play_circle" color="var(--gg-domain-flexibility)" title="Practice Demos" subtitle="Show a Practice Demo before each game" trailing={<Toggle checked={!s.skipRobot} onChange={v => set({ skipRobot: !v })} label="Practice Demos" />} />
          </ListGroup>
        </div>
        <div style={{ marginTop: 24 }}>
          <ListGroup label="Your plan">
            <ListRow icon="target" title="Top priorities" subtitle={s.selectedPriorities.length ? s.selectedPriorities.map(id => PRIORITIES.find(p => p.id === id).title).join(', ') : 'None selected yet'} onClick={() => tog('p')} trailing={<Edit k="p" />}>
              {open === 'p' && <div style={pad}><Meta>Up to 3 ({s.selectedPriorities.length}/3)</Meta><div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>{PRIORITIES.map(p => <OptionChip key={p.id} icon={p.icon} color={`var(--gg-domain-${p.id})`} selected={s.selectedPriorities.includes(p.id)} onClick={() => onTogglePriority(p.id)}>{p.title}</OptionChip>)}</div></div>}
            </ListRow>
            <ListRow icon="timer" color="var(--gg-domain-memory)" title="Ride length & basics" subtitle={(cal.duration || '10–15 min') + (cal.gender ? ' · ' + cal.gender : '')} onClick={() => tog('d')} trailing={<Edit k="d" />}>
              {open === 'd' && <div style={pad}>
                <Meta>Ride length</Meta><div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>{DURATIONS.map(d => <OptionChip key={d} selected={cal.duration === d} onClick={() => set({ calibration: { ...cal, duration: d } })}>{d}</OptionChip>)}</div>
                <Meta>Gender</Meta><div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 8 }}>{GENDERS.map(g => <OptionChip key={g} selected={cal.gender === g} onClick={() => set({ calibration: { ...cal, gender: g } })}>{g === 'Prefer not say' ? 'Other' : g}</OptionChip>)}</div>
              </div>}
            </ListRow>
          </ListGroup>
        </div>
        <div style={{ marginTop: 24 }}><Button tone="ghost" icon="logout" onClick={onLogout}>Restart Onboarding</Button></div>
      </Screen>
    </PhoneShell>
  );
}
Object.assign(window, { Home, Profile });
