// Brother Bear — Home shell screens.
// Five screens: Inbox · Deals · Deal detail · Earnings · Account.
//
// Each screen calls useStore() to get live state and actions. If no store
// is mounted (canvas mode), useStore() returns null and the screen falls
// back to default data + no-op handlers. So the same screens render
// statically on the design canvas (App Home.html) and interactively in
// the live prototype (Live.html).

const fmt = (n) => '€' + n.toLocaleString('de-DE');  // EU format: 1.000

const labelForInboxStatus = (s) =>
  ({ awaiting: 'AWAITING YOU', drafting: 'DRAFTING', replied: 'REPLIED', closed: 'CLOSED' }[s] || s.toUpperCase());

const labelForDealStatus = (s) =>
  ({
    awaiting: 'AWAITING YOU', drafting: 'IN NEGOTIATION', approved: 'APPROVED',
    active: 'ACTIVE', completed: 'COMPLETED', declined: 'DECLINED',
  }[s] || s.toUpperCase());

// ═════════════════════════════════════════════════════════════
// 01 · INBOX
// ═════════════════════════════════════════════════════════════
function ScreenInbox() {
  const store = useStore();
  const items  = store ? store.filteredInbox : DEFAULT_INBOX;
  const filter = store ? store.inboxFilter : 'All';

  const onChip = store ? store.setInboxFilter : null;
  const onTab  = store ? store.goToTab : null;
  const onRow  = store ? ((it) => it.dealId && store.openDeal(it.dealId, 'inbox')) : null;

  const upNext = (store ? store.deals : DEFAULT_DEALS).find((d) => d.status === 'awaiting');

  return (
    <PaperBg>
      <BBTopBar title="Inbox" meta="TUE · MAY 12" />
      <ScreenScroll>
        {/* Up next deadline strip */}
        {upNext && (
          <DocCard pad="14px 16px" mb={20}>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 4 }}>
              <MonoLabel size={10} tracking={0.18} color={BB.statusWarn}>DEADLINE · 03 DAYS</MonoLabel>
              <MonoLabel size={10}>{upNext.deadline}</MonoLabel>
            </div>
            <div style={{ fontFamily: BB.fontSerif, fontSize: 17, lineHeight: 1.3, color: BB.inkBlack }}>
              {upNext.scope.split(/[·+]/)[0].trim()} due to <span style={{ fontWeight: 400 }}>{upNext.brand}</span>.
            </div>
          </DocCard>
        )}

        <ChipRow
          options={['All', 'Awaiting you', 'Drafting', 'Replied']}
          selected={filter} onSelect={onChip} mb={10}
        />

        <Rule mb={0} />
        {items.length === 0 && (
          <div style={{ padding: '32px 0', textAlign: 'center', fontFamily: BB.fontSerif, color: BB.inkFaint, fontSize: 15 }}>
            Nothing in this view.
          </div>
        )}
        {items.map((it) => (
          <div key={it.id}>
            <button
              onClick={() => onRow && onRow(it)}
              disabled={!onRow}
              style={{
                width: '100%', textAlign: 'left', background: 'transparent',
                border: 'none', padding: 0, margin: 0, fontFamily: 'inherit',
                cursor: (onRow && it.dealId) ? 'pointer' : 'default',
                WebkitTapHighlightColor: 'transparent',
              }}
            >
              <div style={{ display: 'grid', gridTemplateColumns: '1fr auto', gap: 10, padding: '14px 0' }}>
                <div style={{ minWidth: 0 }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4 }}>
                    <MonoLabel size={9} tracking={0.1}>{it.code}</MonoLabel>
                    <span style={{ width: 2, height: 2, background: BB.inkFaint }} />
                    <MonoLabel size={9} tracking={0.1}>{it.time} AGO</MonoLabel>
                  </div>
                  <div style={{
                    fontFamily: BB.fontSans, fontWeight: 700, fontSize: 15,
                    letterSpacing: '-0.005em', color: BB.inkBlack, marginBottom: 2,
                  }}>{it.brand}</div>
                  <div style={{
                    fontFamily: BB.fontSans, fontWeight: 400, fontSize: 13,
                    color: BB.inkSoft, lineHeight: 1.35, marginBottom: 6,
                  }}>{it.subject}</div>
                  <div style={{
                    fontFamily: BB.fontSans, fontWeight: 400, fontSize: 12,
                    color: BB.inkFaint, lineHeight: 1.4,
                    whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
                  }}>{it.preview}</div>
                </div>
                <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 6, flexShrink: 0 }}>
                  <StatusPill kind={it.status}>{labelForInboxStatus(it.status)}</StatusPill>
                </div>
              </div>
            </button>
            <Rule />
          </div>
        ))}
      </ScreenScroll>
      <BBTabBar active="inbox" onTabChange={onTab} />
    </PaperBg>
  );
}

// ═════════════════════════════════════════════════════════════
// 02 · DEALS
// ═════════════════════════════════════════════════════════════
function ScreenDeals() {
  const store  = useStore();
  const deals  = store ? store.filteredDeals : DEFAULT_DEALS;
  const filter = store ? store.dealsFilter : 'All';
  const onChip = store ? store.setDealsFilter : null;
  const onTab  = store ? store.goToTab : null;
  const onCard = store ? ((d) => store.openDeal(d.id, 'deals')) : null;

  const totals = (store ? store.deals : DEFAULT_DEALS).reduce(
    (a, d) => (d.status === 'completed' ? { ...a, closed: a.closed + 1 } : { ...a, active: a.active + 1 }),
    { active: 0, closed: 0 }
  );
  const meta = String(totals.active).padStart(2, '0') + ' ACTIVE · ' + String(totals.closed).padStart(2, '0') + ' CLOSED';

  return (
    <PaperBg>
      <BBTopBar title="Deals" meta={meta} />
      <ScreenScroll>
        <ChipRow
          options={['All', 'Awaiting you', 'In negotiation', 'Approved', 'Completed']}
          selected={filter} onSelect={onChip} mb={14}
        />

        <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
          {deals.length === 0 && (
            <div style={{ padding: '32px 0', textAlign: 'center', fontFamily: BB.fontSerif, color: BB.inkFaint, fontSize: 15 }}>
              Nothing in this view.
            </div>
          )}
          {deals.map((d) => (
            <button key={d.code}
              onClick={() => onCard && onCard(d)}
              disabled={!onCard}
              style={{
                textAlign: 'left', background: 'transparent', border: 'none',
                padding: 0, margin: 0, fontFamily: 'inherit',
                cursor: onCard ? 'pointer' : 'default',
                WebkitTapHighlightColor: 'transparent',
              }}
            >
              <DocCard pad="16px 18px">
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 }}>
                  <MonoLabel size={9} tracking={0.12}>{d.code}</MonoLabel>
                  <StatusPill kind={d.status}>{labelForDealStatus(d.status)}</StatusPill>
                </div>
                <div style={{
                  fontFamily: BB.fontSans, fontWeight: 700, fontSize: 17,
                  letterSpacing: '-0.01em', color: BB.inkBlack, marginBottom: 2,
                }}>{d.brand}</div>
                <div style={{
                  fontFamily: BB.fontSans, fontSize: 12, color: BB.inkSoft, marginBottom: 14,
                }}>{d.scope}</div>

                <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginBottom: 10 }}>
                  <span style={{
                    fontFamily: BB.fontSerif, fontSize: 32, lineHeight: 1, color: BB.inkBlack,
                    letterSpacing: '-0.005em',
                  }}>{fmt(d.fee)}</span>
                  <MonoLabel size={9} tracking={0.12}>EUR</MonoLabel>
                </div>

                <Rule mb={10} color={BB.lineSoft} />
                <MonoLabel size={10}>DEADLINE · {d.deadline}</MonoLabel>
              </DocCard>
            </button>
          ))}
        </div>
      </ScreenScroll>
      <BBTabBar active="deals" onTabChange={onTab} />
    </PaperBg>
  );
}

// ═════════════════════════════════════════════════════════════
// 03 · DEAL DETAIL — the presentation of a deal
// ═════════════════════════════════════════════════════════════
function ScreenDealDetail({ dealId }) {
  const store = useStore();
  const deal  = (store && store.findDeal(dealId || '0142')) || DEFAULT_DEALS[0];
  const onBack    = store ? store.goBack : null;
  const onTab     = store ? store.goToTab : null;
  const onApprove = store ? (() => store.approveDeal(deal.id)) : null;
  const onDecline = store ? (() => store.declineDeal(deal.id)) : null;

  const isApproved = deal.status === 'approved';

  return (
    <PaperBg>
      <BBTopBar title="Deal" meta={deal.code} back onBack={onBack} />

      <ScreenScroll pad={24}>
        {/* Hero */}
        <Eyebrow mb={6}>BRAND</Eyebrow>
        <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 12 }}>
          <div style={{
            fontFamily: BB.fontSans, fontWeight: 700, fontSize: 30,
            lineHeight: 1.05, letterSpacing: '-0.02em', color: BB.inkBlack,
          }}>{deal.brand}</div>
          <div style={{ transform: 'rotate(-3deg)', flexShrink: 0, marginTop: 4 }}>
            <StatusPill kind={deal.status}>{labelForDealStatus(deal.status)}</StatusPill>
          </div>
        </div>
        <div style={{
          fontFamily: BB.fontSerif, fontSize: 17, lineHeight: 1.35,
          color: BB.inkSoft, marginTop: 8, letterSpacing: '-0.005em',
        }}>{deal.scope}.</div>

        {/* Fee block */}
        <DocCard pad="18px 20px" mt={22}>
          <Eyebrow mb={2}>FEE</Eyebrow>
          <BigNumeral value={fmt(deal.fee)} unit="EUR" size={56} />
        </DocCard>

        {/* Ari's summary */}
        <Eyebrow mt={28} mb={8}>SUMMARY · BY ARI</Eyebrow>
        <div style={{
          fontFamily: BB.fontSerif, fontSize: 16, lineHeight: 1.45,
          color: BB.inkBlack, letterSpacing: '-0.005em',
        }}>
          {deal.summary}
        </div>

        {/* Timeline */}
        <Eyebrow mt={28} mb={12}>TIMELINE</Eyebrow>
        <div>
          {deal.timeline.map((t, i) => (
            <div key={t.date + i} style={{
              display: 'grid', gridTemplateColumns: '74px 14px 1fr',
              alignItems: 'center', gap: 0, padding: '10px 0',
              borderTop: i === 0 ? `1px solid ${BB.inkBlack}` : 'none',
              borderBottom: `1px solid ${BB.lineSoft}`,
            }}>
              <MonoLabel size={10} tracking={0.1}>{t.date}</MonoLabel>
              <div style={{ display: 'flex', justifyContent: 'center' }}>
                <span style={{
                  width: t.state === 'now' ? 9 : 6,
                  height: t.state === 'now' ? 9 : 6,
                  background: t.state === 'next' ? 'transparent' : BB.inkBlack,
                  border: `1px solid ${BB.inkBlack}`,
                  borderRadius: 0,
                  transform: t.state === 'now' ? 'rotate(45deg)' : 'none',
                }} />
              </div>
              <div style={{
                fontFamily: BB.fontSans, fontSize: 14,
                fontWeight: t.state === 'now' ? 700 : 400,
                color: t.state === 'next' ? BB.inkSoft : BB.inkBlack,
              }}>{t.label}</div>
            </div>
          ))}
        </div>

        {/* Documents */}
        <Eyebrow mt={28} mb={8}>DOCUMENTS</Eyebrow>
        <Rule />
        {deal.documents.map((d) => (
          <div key={d.code}>
            <div style={{ display: 'grid', gridTemplateColumns: '24px 1fr auto 14px', alignItems: 'center', gap: 12, padding: '12px 0' }}>
              <MonoLabel size={10}>{d.code}</MonoLabel>
              <div style={{ fontFamily: BB.fontSans, fontWeight: 600, fontSize: 14, color: BB.inkBlack }}>{d.name}</div>
              <MonoLabel size={9} tracking={0.1}>{d.meta}</MonoLabel>
              <svg width="8" height="14" viewBox="0 0 8 14"><path d="M1 1l6 6-6 6" stroke={BB.inkFaint} strokeWidth="1.4" fill="none" strokeLinecap="round"/></svg>
            </div>
            <Rule />
          </div>
        ))}

        {isApproved ? (
          <div style={{
            marginTop: 28, padding: '28px 16px',
            display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8,
          }}>
            <div style={{
              transform: 'rotate(-6deg)',
              border: `3px solid ${BB.oliveDeep}`,
              padding: '14px 26px',
              outline: `1px solid ${BB.oliveDeep}`, outlineOffset: 8,
            }}>
              <div style={{
                fontFamily: BB.fontSans, fontWeight: 700, fontSize: 28,
                letterSpacing: '0.16em', color: BB.oliveDeep, lineHeight: 1.1,
              }}>APPROVED</div>
              <div style={{
                fontFamily: BB.fontMono, fontSize: 9, fontWeight: 500,
                letterSpacing: '0.2em', color: BB.oliveDeep,
                textAlign: 'center', marginTop: 6,
              }}>BROTHER · BEAR · 26</div>
            </div>
            <div style={{
              marginTop: 10,
              fontFamily: BB.fontSerif, fontSize: 15, color: BB.inkSoft,
              textAlign: 'center', letterSpacing: '-0.005em',
            }}>Reply sent to {deal.brand}.</div>
          </div>
        ) : (
          <>
            <PrimaryButton label="Approve & send" code="01" mt={28} onClick={onApprove} />
            <button
              onClick={() => onDecline && onDecline()}
              disabled={!onDecline}
              style={{
                display: 'block', width: '100%', textAlign: 'center',
                marginTop: 14, padding: 0, border: 'none', background: 'transparent',
                fontFamily: BB.fontSans, fontSize: 13, color: BB.inkFaint,
                textDecoration: 'underline', textUnderlineOffset: 3,
                cursor: onDecline ? 'pointer' : 'default',
              }}
            >Decline</button>
          </>
        )}

        {/* footer mono row */}
        <div style={{ marginTop: 36 }}>
          <Rule />
          <div style={{ display: 'flex', justifyContent: 'space-between', padding: '10px 0' }}>
            <MonoLabel size={10}>FILE · HELGI-JONSSON</MonoLabel>
            <MonoLabel size={10}>OPENED · MAY 12 · 2026</MonoLabel>
          </div>
          <Rule />
        </div>
      </ScreenScroll>

      <BBTabBar active="deals" onTabChange={onTab} />
    </PaperBg>
  );
}

// ═════════════════════════════════════════════════════════════
// 04 · EARNINGS
// ═════════════════════════════════════════════════════════════
function ScreenEarnings() {
  const store  = useStore();
  const onTab  = store ? store.goToTab : null;
  const period = store ? store.earningsPeriod : 'MTD';
  const onChip = store ? store.setEarningsPeriod : null;

  const settled = [
    { code: 'DEAL · 0138', brand: 'NORSE PROJECTS', amt: 2800 },
    { code: 'DEAL · 0137', brand: 'AESOP',           amt: 4800 },
    { code: 'DEAL · 0135', brand: 'ARMEDANGELS',     amt: 3500 },
    { code: 'DEAL · 0133', brand: 'ASKET',           amt: 2500 },
  ];
  const upcoming = [
    { date: 'MAY 22', brand: 'AESOP',          amt: 4800 },
    { date: 'MAY 30', brand: 'NORSE PROJECTS', amt: 2800 },
    { date: 'JUN 09', brand: 'ON RUNNING',     amt: 5700 },
  ];

  return (
    <PaperBg>
      <BBTopBar title="Earnings" meta="MAY · 2026" />
      <ScreenScroll>
        <ChipRow options={['MTD', 'QTD', 'YTD', 'All']} selected={period} onSelect={onChip} mb={20} />

        <Eyebrow mb={4}>EARNED · MAY</Eyebrow>
        <BigNumeral value="€13.600" unit="EUR" size={56} />
        <div style={{
          fontFamily: BB.fontSerif, fontSize: 16, color: BB.inkSoft,
          marginTop: 4, marginBottom: 28, letterSpacing: '-0.005em',
        }}>4 deals settled. 3 in flight.</div>

        <Eyebrow mb={0}>BY DEAL · MAY</Eyebrow>
        <Rule mt={8} />
        {settled.map((d) => (
          <div key={d.code}>
            <div style={{ display: 'grid', gridTemplateColumns: '90px 1fr auto', alignItems: 'center', gap: 10, padding: '12px 0' }}>
              <MonoLabel size={10}>{d.code}</MonoLabel>
              <div style={{ fontFamily: BB.fontSans, fontWeight: 600, fontSize: 14, color: BB.inkBlack }}>{d.brand}</div>
              <span style={{ fontFamily: BB.fontSerif, fontSize: 18, color: BB.inkBlack, letterSpacing: '-0.005em' }}>{fmt(d.amt)}</span>
            </div>
            <Rule color={BB.lineSoft} />
          </div>
        ))}

        <Eyebrow mt={28} mb={0}>UPCOMING</Eyebrow>
        <Rule mt={8} />
        {upcoming.map((u) => (
          <div key={u.date}>
            <div style={{ display: 'grid', gridTemplateColumns: '70px 1fr auto', alignItems: 'center', gap: 10, padding: '12px 0' }}>
              <MonoLabel size={10}>{u.date}</MonoLabel>
              <div style={{ fontFamily: BB.fontSans, fontWeight: 600, fontSize: 14, color: BB.inkBlack }}>{u.brand}</div>
              <span style={{ fontFamily: BB.fontSerif, fontSize: 16, color: BB.inkSoft, letterSpacing: '-0.005em' }}>{fmt(u.amt)}</span>
            </div>
            <Rule color={BB.lineSoft} />
          </div>
        ))}

        <div style={{ marginTop: 32, marginBottom: 8 }}>
          <Rule />
          <div style={{ display: 'flex', justifyContent: 'space-between', padding: '10px 0' }}>
            <MonoLabel size={10}>YTD · €52.310</MonoLabel>
            <MonoLabel size={10}>2026 · 14 DEALS</MonoLabel>
          </div>
          <Rule />
        </div>
      </ScreenScroll>
      <BBTabBar active="earnings" onTabChange={onTab} />
    </PaperBg>
  );
}

// ═════════════════════════════════════════════════════════════
// 05 · ACCOUNT
// ═════════════════════════════════════════════════════════════
function ScreenAccount() {
  const store = useStore();
  const user  = store ? store.user : DEFAULT_USER;
  const onTab = store ? store.goToTab : null;

  const settings = [
    { code: '01', label: 'Rate floor',         value: fmt(user.rateFloor) },
    { code: '02', label: 'Categories',         value: 'Lifestyle · Fashion · +1' },
    { code: '03', label: 'Connected inbox',    value: 'Gmail · helgi@…' },
    { code: '04', label: 'Forwarding address', value: 'agent@brotherbear.co' },
    { code: '05', label: 'Notifications',      value: 'On' },
    { code: '06', label: 'Support',            value: 'hello@brother-bear.com' },
    { code: '07', label: 'Sign out',           value: '' },
  ];

  const initials = user.name.split(' ').map((p) => p[0]).join('').slice(0, 2).toUpperCase();

  return (
    <PaperBg>
      <BBTopBar title="Account" meta="EST · 2026" />
      <ScreenScroll>
        <DocCard pad="18px 18px" mb={26}>
          <div style={{ display: 'grid', gridTemplateColumns: '64px 1fr', gap: 14, alignItems: 'center' }}>
            <div style={{
              width: 64, height: 64,
              border: `1px solid ${BB.inkBlack}`,
              background: BB.paperDeep,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontFamily: BB.fontSans, fontWeight: 700, fontSize: 22, letterSpacing: '-0.01em',
              color: BB.inkBlack,
            }}>{initials}</div>
            <div>
              <div style={{ fontFamily: BB.fontSans, fontWeight: 700, fontSize: 18, color: BB.inkBlack, lineHeight: 1.1, marginBottom: 4 }}>{user.name}</div>
              <div style={{ marginBottom: 8 }}>
                <MonoLabel size={11}>{user.handle.toUpperCase()}</MonoLabel>
              </div>
              <div style={{ display: 'inline-block' }}>
                <StatusPill kind="approved">MEMBER · APR 30 · 2026</StatusPill>
              </div>
            </div>
          </div>
        </DocCard>

        <Eyebrow mb={0}>SETTINGS</Eyebrow>
        <Rule mt={8} />
        {settings.map((s, i) => (
          <div key={s.code}>
            <div style={{ display: 'grid', gridTemplateColumns: '32px 1fr auto 14px', alignItems: 'center', gap: 10, padding: '14px 0' }}>
              <MonoLabel size={10}>{s.code}</MonoLabel>
              <div style={{
                fontFamily: BB.fontSans, fontWeight: 600, fontSize: 14,
                color: s.code === '07' ? BB.statusStop : BB.inkBlack,
              }}>{s.label}</div>
              <div style={{
                fontFamily: BB.fontSans, fontSize: 13, color: BB.inkFaint,
                whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', maxWidth: 160,
              }}>{s.value}</div>
              <svg width="8" height="14" viewBox="0 0 8 14"><path d="M1 1l6 6-6 6" stroke={BB.inkFaint} strokeWidth="1.4" fill="none" strokeLinecap="round"/></svg>
            </div>
            <Rule color={i === settings.length - 1 ? BB.inkBlack : BB.lineSoft} />
          </div>
        ))}

        <div style={{ marginTop: 32 }}>
          <Rule />
          <div style={{ display: 'flex', justifyContent: 'space-between', padding: '10px 0' }}>
            <MonoLabel size={10}>FILE · HELGI-JONSSON</MonoLabel>
            <MonoLabel size={10}>OPENED · APR 30 · 2026</MonoLabel>
          </div>
          <Rule />
          <div style={{
            marginTop: 24, textAlign: 'center',
            fontFamily: BB.fontSans, fontWeight: 700, fontSize: 9,
            letterSpacing: '0.32em', color: BB.inkFaint, textTransform: 'uppercase',
          }}>BROTHER · BEAR · 26</div>
        </div>
      </ScreenScroll>
      <BBTabBar active="account" onTabChange={onTab} />
    </PaperBg>
  );
}

Object.assign(window, {
  ScreenInbox, ScreenDeals, ScreenDealDetail, ScreenEarnings, ScreenAccount,
});
