// Loop MVP — Skills, Compare, Tasks, Notifications, Dataroom, Settings, More

const Do = () => window.LOOP_DATA;

// ─────────────────────────────────────────────────────────────
// SkillsScreen — skills library
// ─────────────────────────────────────────────────────────────
function SkillsScreen({ persona, go }) {
  const skills = Do().skills;
  return (
    <Screen>
      <Header back={() => go('more')} title="Skills library" eyebrow="Reusable building blocks" />
      <div style={{ padding: '8px 22px 0' }}>
        <p style={{ fontSize: 15, color: 'var(--slate)', lineHeight: 1.45 }}>
          Skills are the verbs your agents speak. Share, fork, and combine them.
        </p>
      </div>
      <Section eyebrow="Built-in" title="" style={{ marginTop: 16 }}>
        {skills.filter(s => !s.custom).map((s, i, arr) => (
          <Card key={s.id} style={{ marginBottom: 10, padding: 20 }}>
            <div style={{ display: 'flex', alignItems: 'flex-start', gap: 14 }}>
              <div style={{ width: 44, height: 44, borderRadius: 14, background: 'var(--canvas-whisper)',
                display: 'inline-flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                <Icon name="zap" size={20} />
              </div>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 16, fontWeight: 500, letterSpacing: '-0.01em' }}>{s.name}</div>
                <div style={{ fontSize: 13, color: 'var(--slate)', marginTop: 4, lineHeight: 1.4 }}>{s.desc}</div>
                <div style={{ marginTop: 12, display: 'flex', alignItems: 'center', gap: 10 }}>
                  <Chip>{s.uses} runs · this month</Chip>
                  <span style={{ fontSize: 11, color: 'var(--slate)', textTransform: 'uppercase', letterSpacing: '0.04em' }}>{s.by}</span>
                </div>
              </div>
            </div>
          </Card>
        ))}
      </Section>

      <Section eyebrow="Custom" title="Yours and your team's" style={{ marginTop: 22, paddingBottom: 24 }}
        action={<Button size="sm" variant="signal">Author</Button>}>
        {skills.filter(s => s.custom).map((s) => (
          <Card key={s.id} style={{ marginBottom: 10, padding: 20 }}>
            <div style={{ display: 'flex', alignItems: 'flex-start', gap: 14 }}>
              <div style={{ width: 44, height: 44, borderRadius: 14, background: 'var(--loop-orange-light)',
                display: 'inline-flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                <Icon name="zap" size={20} color="var(--white)" />
              </div>
              <div style={{ flex: 1 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                  <div style={{ fontSize: 16, fontWeight: 500, letterSpacing: '-0.01em' }}>{s.name}</div>
                  <Chip tone="warning">Custom</Chip>
                </div>
                <div style={{ fontSize: 13, color: 'var(--slate)', marginTop: 4, lineHeight: 1.4 }}>{s.desc}</div>
                <div style={{ marginTop: 12, fontSize: 11, color: 'var(--slate)',
                  textTransform: 'uppercase', letterSpacing: '0.04em' }}>{s.by} · {s.uses} runs</div>
              </div>
            </div>
          </Card>
        ))}
      </Section>
    </Screen>
  );
}

// ─────────────────────────────────────────────────────────────
// CompareScreen — side-by-side comparative analysis
// ─────────────────────────────────────────────────────────────
function CompareScreen({ persona, go }) {
  const c = Do().compare[persona];
  return (
    <Screen padBottom={130}>
      <Header back={() => go('more')} title="Compare" eyebrow="Comparative analysis" />
      <div style={{ padding: '8px 22px 0' }}>
        <Eyebrow>Subject</Eyebrow>
        <h1 style={{ fontSize: 26, fontWeight: 500, letterSpacing: '-0.025em', margin: '10px 0 0', lineHeight: 1.15 }}>{c.subject}</h1>
        <p style={{ marginTop: 8, color: 'var(--slate)', fontSize: 14 }}>
          {c.items.length} candidates · {c.rubric.length} dimensions · scored by Loop
        </p>
      </div>

      {/* Header row */}
      <div style={{ padding: '20px 22px 8px', display: 'flex', gap: 10 }}>
        <div style={{ flex: '0 0 110px' }} />
        {c.items.map((it, i) => {
          const person = findPerson(it.name);
          return (
            <div key={i} style={{ flex: 1, textAlign: 'center' }}>
              <Avatar initials={it.initials} tint={it.tint} size={56} photo={person ? person.photo : undefined} />
              <div style={{ marginTop: 8, fontSize: 13, fontWeight: 500, lineHeight: 1.2 }}>{it.name}</div>
            </div>
          );
        })}
      </div>

      {/* Matrix */}
      <Card style={{ margin: '8px 22px 0', padding: '4px 16px' }}>
        {c.rubric.map((r, ri) => (
          <div key={ri} style={{
            display: 'flex', gap: 10, padding: '16px 0',
            borderBottom: ri < c.rubric.length - 1 ? '1px solid rgba(20,20,19,0.06)' : 'none',
            alignItems: 'flex-start',
          }}>
            <div style={{ flex: '0 0 110px' }}>
              <Eyebrow>{`0${ri + 1}`}</Eyebrow>
              <div style={{ fontSize: 13, fontWeight: 500, marginTop: 4, letterSpacing: '-0.01em', lineHeight: 1.25 }}>{r}</div>
            </div>
            {c.items.map((it, ii) => (
              <div key={ii} style={{ flex: 1, fontSize: 12, lineHeight: 1.4,
                color: 'var(--ink)', textAlign: 'center', padding: '0 4px' }}>
                {it.notes[ri]}
              </div>
            ))}
          </div>
        ))}
      </Card>

      {/* Loop's read */}
      <Section eyebrow="Loop's read" title="" style={{ marginTop: 22 }}>
        <Card ink style={{ padding: 22 }}>
          <p style={{ fontSize: 16, lineHeight: 1.5, margin: 0 }}>
            {persona === 'principal'
              ? 'Sequoia leads on conviction and board fit but Founders Fund will close two weeks faster. If timing is the gating factor, push Founders Fund. If you want Roelof in your boardroom, hold for Sequoia and accept the slower close.'
              : 'Yara is the safer hire — she has done the scale jump before. Mae has higher ceiling but more risk. If you can absorb six months of ramp uncertainty, hire Mae. If you need the org settled by Q3, hire Yara.'}
          </p>
        </Card>
      </Section>

      <div style={{ position: 'sticky', bottom: 12, marginTop: 24, marginLeft: 0, marginRight: 0, display: 'flex', gap: 10 }}>
        <Button variant="secondary" style={{ flex: 1 }}>Add column</Button>
        <Button variant="primary" full style={{ flex: 2 }}
          icon={<Icon name="sparkles" size={16} color="var(--canvas)" />}>
          Ask Loop to decide
        </Button>
      </div>
    </Screen>
  );
}

// ─────────────────────────────────────────────────────────────
// TasksScreen — to-do list / daily reminders
// ─────────────────────────────────────────────────────────────
function TasksScreen({ persona, go }) {
  const initial = Do().todos[persona];
  const [done, setDone] = React.useState({});
  const toggle = (id) => setDone(d => ({ ...d, [id]: !d[id] }));

  const groups = [
    { key: 'high', label: 'High signal', tone: 'high' },
    { key: 'med', label: 'This week', tone: 'med' },
    { key: 'low', label: 'When you can', tone: 'low' },
  ];

  return (
    <Screen>
      <Header large title="To do" eyebrow={`${initial.length} items · seeded from your meetings`} />

      <Section style={{ marginTop: 12 }}>
        <Card style={{ padding: 18, display: 'flex', alignItems: 'center', gap: 14, background: 'var(--canvas-whisper)' }}>
          <div style={{ width: 44, height: 44, borderRadius: '50%', background: 'var(--ink)',
            display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}>
            <Icon name="sparkles" size={20} color="var(--canvas)" />
          </div>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 14, fontWeight: 500 }}>Daily ritual draft is ready</div>
            <div style={{ fontSize: 12, color: 'var(--slate)' }}>3 high-signal items · 6 min to clear</div>
          </div>
          <SatelliteCTA icon="arrow-right" size={38} />
        </Card>
      </Section>

      {groups.map(g => {
        const list = initial.filter(t => t.priority === g.key);
        if (!list.length) return null;
        return (
          <Section key={g.key} eyebrow={g.label} title="" style={{ marginTop: 18 }}>
            <Card style={{ padding: '4px 20px' }}>
              {list.map((t, i) => (
                <Row key={t.id} divider={i < list.length - 1}
                  leading={<button onClick={() => toggle(t.id)} style={{
                    width: 26, height: 26, borderRadius: '50%',
                    background: done[t.id] ? 'var(--ink)' : 'transparent',
                    border: '1.5px solid var(--ink)', cursor: 'pointer',
                    display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                  }}>
                    {done[t.id] && <Icon name="check" size={14} color="var(--canvas)" />}
                  </button>}
                  title={<span style={{ textDecoration: done[t.id] ? 'line-through' : 'none',
                    color: done[t.id] ? 'var(--slate)' : 'var(--ink)' }}>{t.body}</span>}
                  subtitle={`${t.from} · ${t.due}`}
                  trailing={<Dot tone={t.due.includes('Overdue') ? 'high' : g.tone} />} />
              ))}
            </Card>
          </Section>
        );
      })}
      <div style={{ height: 24 }} />
    </Screen>
  );
}

// ─────────────────────────────────────────────────────────────
// NotificationsScreen — smart digest + signals
// ─────────────────────────────────────────────────────────────
function NotificationsScreen({ persona, go }) {
  const notifs = Do().notifications[persona];
  const groups = [
    { key: 'high', label: 'Signal · act today' },
    { key: 'med', label: 'This morning' },
    { key: 'low', label: 'Tracked' },
  ];

  const kindIcon = { brief: 'file-text', commit: 'eye', risk: 'alert-triangle', digest: 'sun', crm: 'database' };

  return (
    <Screen>
      <Header back={() => go('home')} title="Notifications" eyebrow="Signal, not noise"
        trailing={<button style={{ padding: '8px 12px', borderRadius: 999, border: '1.5px solid var(--ink)',
          background: 'transparent', cursor: 'pointer', fontSize: 12, fontWeight: 500 }}>Clear</button>} />

      <div style={{ padding: '8px 22px 4px' }}>
        <p style={{ fontSize: 14, color: 'var(--slate)' }}>
          Loop suppresses 87% of typical app noise. Only what changes your day is here.
        </p>
      </div>

      {groups.map(g => {
        const list = notifs.filter(n => n.signal === g.key);
        if (!list.length) return null;
        return (
          <Section key={g.key} eyebrow={g.label} title="" style={{ marginTop: 18 }}>
            {list.map((n, i) => (
              <Card key={n.id} style={{ marginBottom: 10, padding: 18 }}>
                <div style={{ display: 'flex', gap: 14, alignItems: 'flex-start' }}>
                  <div style={{ width: 40, height: 40, borderRadius: '50%',
                    background: n.signal === 'high' ? 'var(--loop-orange)' : 'var(--canvas-whisper)',
                    color: n.signal === 'high' ? 'var(--white)' : 'var(--ink)',
                    display: 'inline-flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                    <Icon name={kindIcon[n.kind]} size={18} color={n.signal === 'high' ? 'var(--white)' : 'var(--ink)'} />
                  </div>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: 14, lineHeight: 1.45 }}>{n.body}</div>
                    <div style={{ marginTop: 8, display: 'flex', alignItems: 'center', gap: 8 }}>
                      <span style={{ fontSize: 11, color: 'var(--slate)', textTransform: 'uppercase', letterSpacing: '0.04em' }}>{n.kind}</span>
                      <span style={{ fontSize: 11, color: 'var(--slate)' }}>·</span>
                      <span style={{ fontSize: 11, color: 'var(--slate)' }}>{n.when}</span>
                    </div>
                  </div>
                </div>
              </Card>
            ))}
          </Section>
        );
      })}
      <div style={{ height: 24 }} />
    </Screen>
  );
}

// ─────────────────────────────────────────────────────────────
// DataroomScreen — secure document hub
// ─────────────────────────────────────────────────────────────
function DataroomScreen({ persona, go }) {
  const docs = Do().dataroom;
  const folders = {};
  docs.forEach(d => { (folders[d.folder] = folders[d.folder] || []).push(d); });
  const [view, setView] = React.useState('grid');

  const kindIcon = { pdf: 'file-text', xlsx: 'file-spreadsheet', doc: 'file-text' };
  const kindTint = { pdf: '#B12318', xlsx: '#1F7A4D', doc: '#3860BE' };

  return (
    <Screen>
      <Header large title="Dataroom" eyebrow="Your working context"
        trailing={<button style={{ width: 40, height: 40, borderRadius: '50%', background: 'var(--ink)', color: 'var(--canvas)',
          border: 'none', cursor: 'pointer', display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}>
          <Icon name="plus" size={20} color="var(--canvas)" />
        </button>} />

      <div style={{ padding: '14px 22px 8px', display: 'flex', alignItems: 'center', gap: 10 }}>
        <div style={{ flex: 1, display: 'flex', alignItems: 'center', gap: 10, padding: '10px 14px',
          background: 'var(--canvas-lifted)', borderRadius: 999 }}>
          <Icon name="search" size={16} color="var(--slate)" />
          <input placeholder="Ask the dataroom…"
            style={{ flex: 1, border: 'none', outline: 'none', background: 'transparent',
              fontFamily: 'var(--font-sans)', fontSize: 14, fontWeight: 450 }} />
        </div>
        <button onClick={() => setView(view === 'grid' ? 'list' : 'grid')} style={{
          width: 40, height: 40, borderRadius: 12, background: 'var(--canvas-lifted)',
          border: 'none', cursor: 'pointer', display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}>
          <Icon name={view === 'grid' ? 'list' : 'grid'} size={18} />
        </button>
      </div>

      {/* Sources */}
      <Section eyebrow="Sources" title="" style={{ marginTop: 10 }}>
        <div style={{ display: 'flex', gap: 10, overflowX: 'auto', padding: '0 22px 4px', margin: '0 -22px' }}>
          {[
            { name: 'Google Drive', count: '4,210 files', status: 'synced' },
            { name: 'Microsoft 365', count: '2,860 files', status: 'synced' },
            { name: 'Salesforce', count: '184 records', status: 'synced' },
            { name: 'Greenhouse', count: '38 candidates', status: 'synced' },
          ].map((s, i) => (
            <Card key={i} style={{ minWidth: 170, padding: 14 }}>
              <Chip tone="success"><Dot tone="success" size={6} /> {s.status}</Chip>
              <div style={{ marginTop: 10, fontSize: 14, fontWeight: 500 }}>{s.name}</div>
              <div style={{ fontSize: 12, color: 'var(--slate)' }}>{s.count}</div>
            </Card>
          ))}
        </div>
      </Section>

      {Object.entries(folders).map(([fname, list]) => (
        <Section key={fname} eyebrow={fname} title="" style={{ marginTop: 18 }}>
          {view === 'grid' ? (
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
              {list.map(d => (
                <Card key={d.id} style={{ padding: 16 }}>
                  <div style={{ width: 44, height: 44, borderRadius: 12,
                    background: kindTint[d.kind], color: 'var(--white)',
                    display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}>
                    <Icon name={kindIcon[d.kind]} size={20} color="var(--white)" />
                  </div>
                  <div style={{ marginTop: 12, fontSize: 13, fontWeight: 500, lineHeight: 1.25,
                    overflow: 'hidden', textOverflow: 'ellipsis', display: '-webkit-box',
                    WebkitLineClamp: 2, WebkitBoxOrient: 'vertical' }}>{d.name}</div>
                  <div style={{ marginTop: 6, fontSize: 11, color: 'var(--slate)' }}>{d.meta}</div>
                </Card>
              ))}
            </div>
          ) : (
            <Card style={{ padding: '4px 20px' }}>
              {list.map((d, i) => (
                <Row key={d.id} divider={i < list.length - 1}
                  leading={<div style={{ width: 38, height: 38, borderRadius: 10,
                    background: kindTint[d.kind], display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}>
                    <Icon name={kindIcon[d.kind]} size={18} color="var(--white)" /></div>}
                  title={d.name} subtitle={d.meta}
                  trailing={<Icon name="arrow-up-right" size={16} color="var(--slate)" />} />
              ))}
            </Card>
          )}
        </Section>
      ))}
      <div style={{ height: 24 }} />
    </Screen>
  );
}

// ─────────────────────────────────────────────────────────────
// SettingsScreen — integrations + persona profile + custom OS
// ─────────────────────────────────────────────────────────────
function SettingsScreen({ persona, go }) {
  const u = Do()[persona];
  const integrations = Do().integrations;
  const groups = {};
  integrations.forEach(i => { (groups[i.kind] = groups[i.kind] || []).push(i); });

  return (
    <Screen>
      <Header large title="Settings" eyebrow="Your workspace" />

      {/* Profile */}
      <Section style={{ marginTop: 8 }}>
        <Card style={{ padding: 20 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
            <Avatar initials={u.initials} tint={u.tint} size={56} />
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 17, fontWeight: 500, letterSpacing: '-0.01em' }}>{u.name}</div>
              <div style={{ fontSize: 13, color: 'var(--slate)' }}>{u.role}</div>
            </div>
            <Icon name="chevron-right" size={18} color="var(--slate)" />
          </div>
        </Card>
      </Section>

      {/* Custom OS */}
      <Section eyebrow="Custom OS" title="Your workspace, your way" style={{ marginTop: 18 }}>
        <Card style={{ padding: '4px 20px' }}>
          <Row leading={<Icon name="layout" size={20} />} title="Layout"
            subtitle={persona === 'principal' ? 'Principal · meetings-first' : 'Moderator · pipeline-first'}
            trailing={<Icon name="chevron-right" size={16} color="var(--slate)" />} />
          <Row leading={<Icon name="bell" size={20} />} title="Daily rituals"
            subtitle={persona === 'principal' ? '06:30 brief · 21:00 close-out' : '08:00 pipeline · 18:00 close-out'}
            trailing={<Icon name="chevron-right" size={16} color="var(--slate)" />} />
          <Row leading={<Icon name="users" size={20} />} title="My people view"
            subtitle="4 groups · auto-grouped from CRM"
            trailing={<Icon name="chevron-right" size={16} color="var(--slate)" />}
            onClick={() => go('people')} />
          <Row leading={<Icon name="palette" size={20} />} title="Appearance"
            subtitle="Cream · auto · large type off"
            divider={false}
            trailing={<Icon name="chevron-right" size={16} color="var(--slate)" />} />
        </Card>
      </Section>

      {/* Integrations */}
      {Object.entries(groups).map(([kind, list]) => (
        <Section key={kind} eyebrow={kind} title="" style={{ marginTop: 18 }}>
          <Card style={{ padding: '4px 20px' }}>
            {list.map((it, i) => (
              <Row key={it.id} divider={i < list.length - 1}
                leading={<div style={{ width: 40, height: 40, borderRadius: 10,
                  background: 'var(--canvas-whisper)',
                  display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                  fontSize: 11, fontWeight: 700, letterSpacing: '0.04em' }}>
                  {it.name.split(' ').map(w => w[0]).slice(0, 2).join('')}
                </div>}
                title={it.name} subtitle={it.detail}
                trailing={
                  it.status === 'connected'
                    ? <Chip tone="success"><Dot tone="success" size={6} /> Connected</Chip>
                    : it.status === 'available'
                    ? <Button size="sm" variant="secondary">Connect</Button>
                    : <Chip tone="muted">Coming soon</Chip>
                } />
            ))}
          </Card>
        </Section>
      ))}

      <Section eyebrow="Account" title="" style={{ marginTop: 18, paddingBottom: 24 }}>
        <Card style={{ padding: '4px 20px' }}>
          <Row leading={<Icon name="shield" size={20} />} title="Privacy & data"
            subtitle="Recording consent, retention, regions"
            trailing={<Icon name="chevron-right" size={16} color="var(--slate)" />} />
          <Row leading={<Icon name="help-circle" size={20} />} title="Help & feedback"
            divider={false}
            trailing={<Icon name="chevron-right" size={16} color="var(--slate)" />} />
        </Card>
      </Section>
    </Screen>
  );
}

// ─────────────────────────────────────────────────────────────
// MoreScreen — drawer for secondary destinations
// ─────────────────────────────────────────────────────────────
function MoreScreen({ persona, go }) {
  const u = Do()[persona];
  const sections = [
    {
      label: 'Workspace',
      items: [
        { id: 'dataroom', name: 'Dataroom', sub: 'Your working context', icon: 'folder' },
        { id: 'tasks', name: 'To do list', sub: 'Daily reminders, seeded from meetings', icon: 'check-square' },
        { id: 'notifications', name: 'Notifications', sub: 'Signal, not noise', icon: 'bell' },
      ],
    },
    {
      label: 'Intelligence',
      items: [
        { id: 'compare', name: 'Comparative analysis', sub: 'Candidates, vendors, deals, proposals', icon: 'columns' },
        { id: 'skills', name: 'Skills library', sub: '8 skills · 2 custom', icon: 'zap' },
        { id: 'agent-builder', name: 'Build an agent', sub: 'No-code agent builder', icon: 'sparkles' },
      ],
    },
    {
      label: 'You',
      items: [
        { id: 'settings', name: 'Settings & integrations', sub: '8 connected · 1 coming soon', icon: 'settings' },
      ],
    },
  ];
  return (
    <Screen>
      <Header large title="More" />

      <Section style={{ marginTop: 8 }}>
        <Card style={{ padding: 22, position: 'relative', overflow: 'hidden' }} ink>
          <Eyebrow style={{ color: 'var(--canvas)' }}>Your custom OS</Eyebrow>
          <h2 style={{ fontSize: 22, fontWeight: 500, letterSpacing: '-0.02em', marginTop: 12, lineHeight: 1.25, maxWidth: 280 }}>
            {persona === 'principal' ? 'Tuned for the principal' : 'Tuned for the moderator'}
          </h2>
          <p style={{ marginTop: 10, fontSize: 13, color: 'rgba(252,251,250,0.65)', lineHeight: 1.4, maxWidth: 290 }}>
            {persona === 'principal'
              ? 'Investor relations, board prep, key relationships. 06:30 brief, 21:00 close-out.'
              : 'Pipeline keeper, panel summaries, comparative analysis. 08:00 pipeline brief.'}
          </p>
          <div style={{ position: 'absolute', right: -30, top: -30, width: 130, height: 130,
            borderRadius: '50%', border: '1.2px solid rgba(243,115,56,0.4)' }} />
        </Card>
      </Section>

      {sections.map((s, si) => (
        <Section key={si} eyebrow={s.label} title="" style={{ marginTop: 22 }}>
          <Card style={{ padding: '4px 20px' }}>
            {s.items.map((it, i) => (
              <Row key={it.id} divider={i < s.items.length - 1}
                leading={<div style={{ width: 40, height: 40, borderRadius: 12,
                  background: 'var(--canvas-whisper)',
                  display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}>
                  <Icon name={it.icon} size={20} /></div>}
                title={it.name} subtitle={it.sub}
                trailing={<Icon name="chevron-right" size={18} color="var(--slate)" />}
                onClick={() => go(it.id)} />
            ))}
          </Card>
        </Section>
      ))}
      <div style={{ height: 24 }} />
    </Screen>
  );
}

Object.assign(window, {
  SkillsScreen, CompareScreen, TasksScreen, NotificationsScreen, DataroomScreen, SettingsScreen, MoreScreen,
});
