// Otto App · Screen 1 (Home), Screen 2 (Inbox), Screen 4 (Pipeline)

// ── HOME ─────────────────────────────────────────────────────
const HomeScreen = () => {
  const myDeals = DEALS.filter(d => d.owner === 'james');
  const myTasks = TASKS;
  const totalARR = myDeals.reduce((s, d) => s + d.amount, 0);
  const closingThisQ = myDeals.filter(d => ['Negotiation','Closing'].includes(d.stage));
  return (
    <>
      <PageHeader
        eyebrow="Monday · May 8"
        title="Good morning, James"
        sub="3 deals advancing this week. Otto handled 14 inbound touches overnight."
        actions={<><Btn leadingIcon="plus">Log activity</Btn><Btn kind="primary" leadingIcon="sparkle">Ask Otto</Btn></>}
      />
      <div style={{ padding: 28, display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14 }}>
        <Stat label="Pipeline · Q2" value={`$${(totalARR/1000).toFixed(0)}K`} sub={`${myDeals.length} open`} />
        <Stat label="Closing this week" value={closingThisQ.length} sub="2 awaiting signature" trend="up" />
        <Stat label="Activities · today" value="14" sub="9 by Otto · 5 by you" />
        <Stat label="Open tasks" value={myTasks.length} sub="2 high-priority" trend="warn" />
      </div>
      <div style={{ padding: '0 28px 28px', display: 'grid', gridTemplateColumns: '1.6fr 1fr', gap: 14, alignItems: 'start' }}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
          <Card title="My deals" sub="Sorted by close date" action={<Btn>View pipeline</Btn>}>
            <DealRows deals={myDeals} />
          </Card>
          <Card title="Recent activity" sub="Across your accounts">
            <ActivityRows activities={ACTIVITIES.slice(0, 5)} />
          </Card>
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
          <Card title="Today" sub="From Otto" accent="var(--signal)">
            <div style={{ display: 'flex', flexDirection: 'column', gap: 10, fontSize: 13, lineHeight: 1.55 }}>
              <OttoLine>Carla confirmed verbal on Q-2041 · contract is the only blocker.</OttoLine>
              <OttoLine>Meridian SOW redlines arrived — flagged 3 commercial changes for your review.</OttoLine>
              <OttoLine>Hartwell has gone 3 days without a touch — want me to send a check-in?</OttoLine>
            </div>
          </Card>
          <Card title="Tasks" action={<Btn>View all</Btn>}>
            <TaskRows tasks={myTasks} />
          </Card>
        </div>
      </div>
    </>
  );
};

const Stat = ({ label, value, sub, trend }) => (
  <div style={{ background: 'var(--paper)', border: '1px solid var(--line)', borderRadius: 'var(--r-md)', padding: 16 }}>
    <div className="eyebrow">{label}</div>
    <div style={{ fontSize: 28, fontWeight: 600, letterSpacing: -0.8, marginTop: 6, fontFamily: 'var(--t-display)' }}>{value}</div>
    <div style={{ fontSize: 12, color: trend === 'warn' ? 'var(--signal)' : 'var(--fg-muted)', marginTop: 2 }}>{sub}</div>
  </div>
);

const OttoLine = ({ children }) => (
  <div style={{ display: 'flex', gap: 8, alignItems: 'flex-start' }}>
    <Icon name="sparkle" size={13} color="var(--signal)" />
    <span style={{ flex: 1 }}>{children}</span>
  </div>
);

// ── INBOX ────────────────────────────────────────────────────
const InboxScreen = () => {
  const [filter, setFilter] = React.useState('All');
  const filters = ['All', 'Calls', 'Emails', 'Notes', 'Tasks', 'Otto actions'];
  return (
    <>
      <PageHeader
        eyebrow="Inbox"
        title="Activity feed"
        sub="Every customer-facing touch — captured, attributed, and assigned."
        tabs={filters} activeTab={filter} onTab={setFilter}
        actions={<><Btn leadingIcon="plus">Compose</Btn><Btn kind="primary" leadingIcon="sparkle">Otto</Btn></>}
      />
      <div style={{ padding: 28, display: 'grid', gridTemplateColumns: '1.5fr 1fr', gap: 14, alignItems: 'start' }}>
        <Card title="Recent" sub={`${ACTIVITIES.length} items · all accounts you have access to`} padded={false}>
          <ActivityRows activities={ACTIVITIES} compact={false} />
        </Card>
        <Card title="Unassigned" sub="Otto needs help routing" accent="var(--signal)">
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10, fontSize: 13 }}>
            <UnassignedRow subj="careers@ → unknown sender" hint="Otto: probably partnership inquiry" />
            <UnassignedRow subj="Phone call · (216) 555-0019" hint="Otto: matched no contact" />
          </div>
        </Card>
      </div>
    </>
  );
};

const UnassignedRow = ({ subj, hint }) => (
  <div style={{ padding: 10, background: 'var(--bg)', border: '1px solid var(--line-soft)', borderRadius: 'var(--r-sm)' }}>
    <div style={{ fontWeight: 500 }}>{subj}</div>
    <div style={{ fontSize: 11, color: 'var(--signal)', marginTop: 4, display: 'flex', gap: 6, alignItems: 'center' }}>
      <Icon name="sparkle" size={11} color="var(--signal)" /> {hint}
    </div>
  </div>
);

// ── PIPELINE ────────────────────────────────────────────────
const PipelineScreen = () => {
  return (
    <>
      <PageHeader
        eyebrow="Sales"
        title="Pipeline"
        sub="$237K open across your 5 deals · weighted: $129K"
        actions={<><Btn leadingIcon="plus">New deal</Btn><Btn kind="primary" leadingIcon="sparkle">Forecast with Otto</Btn></>}
      />
      <div style={{ padding: 20, overflowX: 'auto' }}>
        <div style={{ display: 'grid', gridTemplateColumns: `repeat(${STAGES.length}, minmax(260px, 1fr))`, gap: 12 }}>
          {STAGES.map(stage => {
            const stageDeals = DEALS.filter(d => d.stage === stage);
            const sum = stageDeals.reduce((s, d) => s + d.amount, 0);
            return (
              <div key={stage} style={{ background: 'var(--paper-2)', border: '1px solid var(--line-soft)', borderRadius: 'var(--r-md)', padding: 10 }}>
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 10, padding: '4px 4px 8px', borderBottom: '1px solid var(--line-soft)' }}>
                  <div>
                    <div style={{ fontSize: 12, fontWeight: 600 }}>{stage}</div>
                    <div className="eyebrow" style={{ marginTop: 2 }}>{stageDeals.length} · ${(sum/1000).toFixed(0)}K</div>
                  </div>
                </div>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                  {stageDeals.map(d => <DealCard key={d.id} deal={d} />)}
                  {stageDeals.length === 0 && <div style={{ fontSize: 11, color: 'var(--fg-soft)', padding: 8, textAlign: 'center' }}>No deals</div>}
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </>
  );
};

const DealCard = ({ deal }) => {
  const acc = accountById(deal.account);
  const owner = userById(deal.owner);
  return (
    <div style={{ background: 'var(--paper)', border: '1px solid var(--line)', borderRadius: 'var(--r-sm)', padding: 10, boxShadow: 'var(--shadow-sm)' }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 6 }}>
        <div className="eyebrow" style={{ fontSize: 9 }}>{deal.id}</div>
        <Avatar initials={owner.initials} color={owner.color} size={18} />
      </div>
      <div style={{ fontSize: 13, fontWeight: 500, marginTop: 4, lineHeight: 1.3 }}>{acc.name}</div>
      <div style={{ fontSize: 11, color: 'var(--fg-muted)', marginTop: 2 }}>{deal.name.split('·')[1]?.trim() || deal.name}</div>
      <div style={{ marginTop: 10, display: 'flex', alignItems: 'center', justifyContent: 'space-between', fontSize: 11 }}>
        <span style={{ fontFamily: 'var(--t-mono)', color: 'var(--fg)', fontWeight: 600 }}>${(deal.amount/1000).toFixed(0)}K</span>
        <span style={{ color: 'var(--fg-muted)' }}>{deal.closeDate}</span>
      </div>
    </div>
  );
};

// ── Shared row components ────────────────────────────────────
const DealRows = ({ deals }) => (
  <div style={{ margin: -16 }}>
    {deals.map((d, i) => {
      const acc = accountById(d.account);
      return (
        <div key={d.id} style={{
          padding: '12px 16px', display: 'grid',
          gridTemplateColumns: '60px 1fr 100px 120px 90px',
          gap: 12, alignItems: 'center',
          borderTop: i === 0 ? 'none' : '1px solid var(--line-soft)',
          fontSize: 13,
        }}>
          <span className="eyebrow" style={{ fontSize: 9 }}>{d.id}</span>
          <div>
            <div style={{ fontWeight: 500 }}>{acc.name}</div>
            <div style={{ fontSize: 11, color: 'var(--fg-muted)' }}>{d.name.split('·')[1]?.trim()}</div>
          </div>
          <StagePill stage={d.stage} />
          <span style={{ fontFamily: 'var(--t-mono)', fontSize: 12 }}>${(d.amount/1000).toFixed(0)}K · {d.closeDate}</span>
          <span style={{ color: 'var(--fg-muted)', fontSize: 11, textAlign: 'right' }}>{d.lastActivity}</span>
        </div>
      );
    })}
  </div>
);

const ActivityRows = ({ activities, compact = true }) => (
  <div style={{ margin: -16 }}>
    {activities.map((a, i) => {
      const acc = accountById(a.account);
      const typeMap = {
        call:  { color: 'var(--signal)', label: 'Call' },
        email: { color: 'var(--sky)', label: 'Email' },
        task:  { color: 'var(--stage-prop)', label: 'Task' },
        note:  { color: 'var(--fg-muted)', label: 'Note' },
      };
      const t = typeMap[a.type];
      return (
        <div key={a.id} style={{
          padding: '12px 16px', display: 'flex', gap: 12, alignItems: 'flex-start',
          borderTop: i === 0 ? 'none' : '1px solid var(--line-soft)',
          fontSize: 13,
        }}>
          <Pill color="#FFF" bg={t.color}>{t.label}</Pill>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ display: 'flex', gap: 8, alignItems: 'center', flexWrap: 'wrap' }}>
              <span style={{ fontWeight: 500 }}>{a.subject || a.topic}</span>
              {a.byOtto && <Pill color="var(--signal)" bg="var(--signal-soft)">via Otto</Pill>}
              {a.auto && <Pill color="var(--signal)" bg="var(--signal-soft)">auto-detected</Pill>}
            </div>
            <div style={{ fontSize: 11, color: 'var(--fg-muted)', marginTop: 3 }}>
              {acc?.name} {a.dur && `· ${a.dur}`}
            </div>
          </div>
          <span style={{ fontSize: 11, color: 'var(--fg-soft)', fontFamily: 'var(--t-mono)', flexShrink: 0 }}>{a.when}</span>
        </div>
      );
    })}
  </div>
);

const TaskRows = ({ tasks }) => (
  <div style={{ margin: -16, display: 'flex', flexDirection: 'column' }}>
    {tasks.map((t, i) => (
      <label key={t.id} style={{
        padding: '10px 16px', display: 'flex', gap: 10, alignItems: 'center',
        borderTop: i === 0 ? 'none' : '1px solid var(--line-soft)', fontSize: 13,
      }}>
        <input type="checkbox" style={{ width: 14, height: 14, accentColor: 'var(--fg)' }} />
        <div style={{ flex: 1 }}>
          <div>{t.title}</div>
          <div style={{ fontSize: 11, color: 'var(--fg-muted)', marginTop: 2 }}>
            {t.account ? accountById(t.account)?.name : '—'} · {t.due}
          </div>
        </div>
        {t.priority === 'high' && <Pill color="var(--signal)" bg="var(--signal-soft)">High</Pill>}
      </label>
    ))}
  </div>
);

Object.assign(window, { HomeScreen, InboxScreen, PipelineScreen, DealRows, ActivityRows, TaskRows, Stat, OttoLine, DealCard });
