// Overview page — the default landing after sign-in.
// Same shape for Personal and Business accounts; data swaps based on
// active account.

function OverviewPage() {
  const t = window.tokens;
  const [account] = useActiveAccount();
  const profile = ACCOUNTS[account];
  const isBiz = account === 'business';

  const apps = APPS[account];
  const actionItems = apps.filter(a => a.bucket === 'action');
  const muniSlices = sliceByMuni(account);
  const propSlices = sliceByProperty(account);
  const drafts = apps.filter(a => a.bucket === 'draft');
  const activity = ACTIVITY[account];

  const greeting = (() => {
    const h = new Date().getHours();
    if (h < 12) return 'Good morning';
    if (h < 18) return 'Good afternoon';
    return 'Good evening';
  })();
  const today = new Date().toLocaleDateString('en-US', { weekday: 'long', month: 'long', day: 'numeric' });

  return (
    <AccountPage activeNav="overview">
      {/* Hero */}
      <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 24, marginBottom: 28 }}>
        <div>
          <Caption>{today}</Caption>
          <div style={{ fontSize: 36, fontWeight: 500, letterSpacing: -0.6, color: t.color.text, marginTop: 8, lineHeight: 1.1 }}>
            {isBiz ? <>Welcome back, <span style={{ color: t.color.text }}>{profile.short}</span></> : <>{greeting}, {profile.name.split(' ')[0]}</>}
          </div>
          <div style={{ fontSize: 15, color: t.color.muted, marginTop: 8, lineHeight: 1.5, maxWidth: 640 }}>
            {actionItems.length > 0
              ? <>{actionItems.length} {actionItems.length === 1 ? 'thing needs' : 'things need'} your action today. {activity.filter(a => !a.action).length} updates since you last logged in.</>
              : <>Nothing needs you today. You're caught up across {muniSlices.length} {muniSlices.length === 1 ? 'municipality' : 'municipalities'}.</>}
          </div>
        </div>
        <a href="Account-Find.html" style={{ textDecoration: 'none' }}>
          <Button variant="secondary" size="lg" iconAfter={<FluentIcon name="arrow_right" size={16} />}>
            Find Services
          </Button>
        </a>
      </div>

      {/* Action card */}
      {actionItems.length > 0 && (
        <ActionCard items={actionItems} account={account} />
      )}

      {/* Split row: tabbed slices on the left, recent activity on the right. */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 20, marginTop: 24, alignItems: 'flex-start' }}>
        <TabbedSlicesCard
          isBiz={isBiz}
          muniSlices={muniSlices}
          propSlices={propSlices}
          drafts={drafts}
          propertyCount={profile.properties.length}
        />
        <ActivityFeed activity={activity} />
      </div>
    </AccountPage>
  );
}

// ─── Action card (orange-edged Alert-style block) ───────────

function ActionCard({ items, account }) {
  const t = window.tokens;
  return (
    <div style={{
      background: t.color.actionSoft,
      border: `1px solid ${t.color.actionEdge}`,
      borderRadius: t.radius.lg,
      overflow: 'hidden',
    }}>
      <div style={{ padding: '14px 20px', display: 'flex', alignItems: 'center', gap: 10, borderBottom: `1px solid ${t.color.actionEdge}` }}>
        <FluentIcon name="alert" weight="filled" size={20} style={{ color: t.color.action }} />
        <span style={{ fontSize: 15, fontWeight: 600, color: t.color.action }}>
          Needs Your Action · {items.length}
        </span>
      </div>
      <div style={{ background: t.color.bg }}>
        {items.map((it, i) => (
          <div key={i} style={{
            display: 'grid', gridTemplateColumns: '1fr auto', alignItems: 'center', gap: 16,
            padding: '14px 20px',
            borderBottom: i < items.length - 1 ? `1px solid ${t.color.hair}` : 'none',
          }}>
            <div style={{ minWidth: 0 }}>
              <div style={{ fontSize: 15, color: t.color.text, fontWeight: 500, marginBottom: 3 }}>{it.type} · {it.subject}</div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10, fontSize: 12.5, color: t.color.muted }}>
                <span style={{ fontFamily: t.font.mono }}>{it.code}</span>
                <span style={{ width: 3, height: 3, borderRadius: 1.5, background: t.color.dim }} />
                <span>{it.muni}</span>
              </div>
            </div>
            <Button variant="secondary" size="sm" iconAfter={<FluentIcon name="arrow_right" size={14} />}>{it.cta}</Button>
          </div>
        ))}
      </div>
    </div>
  );
}

// ─── Tabbed slices card (combines Properties/Job sites,
//     Municipalities, and Drafts under one roof) ───────────────

function TabbedSlicesCard({ isBiz, muniSlices, propSlices, drafts, propertyCount }) {
  const t = window.tokens;
  const tabs = [
    { key: 'properties', label: isBiz ? 'Job sites' : 'Properties', count: propSlices.length },
    { key: 'munis',      label: 'Municipalities',                   count: muniSlices.length },
    { key: 'drafts',     label: 'Drafts',                           count: drafts.length },
  ];
  const [active, setActive] = React.useState(0);

  // Reset to first tab when the active account flips (drafts.length may
  // shift, but more importantly the property/job-site tab label changes).
  React.useEffect(() => { setActive(0); }, [isBiz]);

  const tab = tabs[active];

  return (
    <Card pad={0}>
      {/* Tab bar */}
      <div style={{ display: 'flex', gap: 0, borderBottom: `1px solid ${t.color.hair}`, padding: '0 10px' }}>
        {tabs.map((tb, i) => {
          const isActive = i === active;
          return (
            <button key={tb.key} onClick={() => setActive(i)}
              style={{
                padding: '14px 12px',
                background: 'transparent', border: 'none',
                borderBottom: `2px solid ${isActive ? t.color.action : 'transparent'}`,
                marginBottom: -1,
                fontFamily: t.font.sans, fontSize: 14, fontWeight: isActive ? 600 : 500,
                color: isActive ? t.color.text : t.color.muted,
                cursor: 'pointer',
                display: 'inline-flex', alignItems: 'center', gap: 8,
              }}>
              {tb.label}
              <span style={{
                fontFamily: t.font.mono, fontSize: 11,
                padding: '1px 7px', borderRadius: 999,
                background: isActive ? t.color.actionSoft : t.color.surfaceHi,
                color: isActive ? t.color.action : t.color.muted,
                minWidth: 20, textAlign: 'center', lineHeight: 1.5,
              }}>{tb.count}</span>
            </button>
          );
        })}
      </div>

      {/* Body */}
      <div>
        {tab.key === 'properties' && propSlices.map((p, i) => (
          <SliceRow key={p.property} row={{
            id: p.property,
            label: p.property,
            sub: p.muni,
            count: p.count,
            action: p.action > 0,
            actionText: p.action > 0 ? `${p.action} need${p.action === 1 ? 's' : ''} action` : null,
            href: `Account-Applications.html?property=${encodeURIComponent(p.property)}`,
          }} last={i === propSlices.length - 1} />
        ))}

        {tab.key === 'munis' && muniSlices.map((m, i) => (
          <SliceRow key={m.muni} row={{
            id: m.muni,
            primary: m.primary,
            label: m.muni,
            count: m.count,
            action: m.action > 0,
            actionText: m.action > 0 ? `${m.action} need${m.action === 1 ? 's' : ''} action` : null,
            href: `Account-Applications.html?muni=${encodeURIComponent(m.muni)}`,
          }} last={i === muniSlices.length - 1} />
        ))}

        {tab.key === 'drafts' && drafts.length === 0 && (
          <div style={{ padding: '40px 20px', textAlign: 'center', color: t.color.muted, fontSize: 13 }}>No drafts saved. Forms auto-save as you go.</div>
        )}
        {tab.key === 'drafts' && drafts.map((d, i) => (
          <DraftRow key={i} draft={d} last={i === drafts.length - 1} />
        ))}
      </div>

      {/* Footer */}
      <div style={{ padding: '12px 18px', borderTop: `1px solid ${t.color.hair}`, background: t.color.surfaceLo }}>
        {tab.key === 'properties' && (isBiz
          ? <Button variant="tertiary" size="sm" iconAfter={<FluentIcon name="arrow_right" size={14} />}>See all {propSlices.length} job sites</Button>
          : <Button variant="tertiary" size="sm" iconBefore={<FluentIcon name="add" size={14} />}>Add a property</Button>)}
        {tab.key === 'munis' && (
          <Button variant="tertiary" size="sm" iconAfter={<FluentIcon name="arrow_right" size={14} />}>Find services in another municipality</Button>
        )}
        {tab.key === 'drafts' && drafts.length > 0 && (
          <Button variant="tertiary" size="sm" iconAfter={<FluentIcon name="arrow_right" size={14} />}>View all drafts in Applications</Button>
        )}
      </div>
    </Card>
  );
}

// ─── Slice row (one drill-in destination) ────────────────────

function SliceRow({ row, last }) {
  const t = window.tokens;
  const [hover, setHover] = React.useState(false);
  return (
    <a href={row.href}
      onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
      style={{
        display: 'grid', gridTemplateColumns: '1fr auto auto auto', alignItems: 'center', gap: 14,
        padding: '12px 18px',
        borderBottom: last ? 'none' : `1px solid ${t.color.hair}`,
        background: hover ? t.color.surfaceLo : 'transparent',
        textDecoration: 'none', color: 'inherit',
        transition: 'background .12s',
      }}>
      <div style={{ minWidth: 0, display: 'flex', alignItems: 'center', gap: 8 }}>
        <span style={{ fontSize: 14.5, color: t.color.text, fontWeight: 500 }}>{row.label}</span>
        {row.primary && <FluentIcon name="star" weight="filled" size={13} style={{ color: t.color.warn }} />}
      </div>
      <div style={{ fontSize: 12.5, color: row.action ? t.color.action : t.color.muted, fontWeight: row.action ? 500 : 400 }}>
        {row.actionText || row.sub || ''}
      </div>
      <div style={{ fontFamily: t.font.mono, fontSize: 12.5, color: t.color.muted, minWidth: 28, textAlign: 'right' }}>
        {row.count}
      </div>
      <FluentIcon name="chevron_right" size={14} style={{ color: hover ? t.color.text : t.color.dim }} />
    </a>
  );
}

// ─── Draft row (used inside the drafts tab) ─────────────────

function DraftRow({ draft, last }) {
  const t = window.tokens;
  const [hover, setHover] = React.useState(false);
  return (
    <a href="#"
      onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
      style={{
        display: 'block',
        padding: '12px 18px',
        borderBottom: last ? 'none' : `1px solid ${t.color.hair}`,
        background: hover ? t.color.surfaceLo : 'transparent',
        textDecoration: 'none', color: 'inherit',
        transition: 'background .12s',
      }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 6, gap: 12 }}>
        <div style={{ minWidth: 0 }}>
          <div style={{ fontSize: 14, fontWeight: 500, color: t.color.text }}>{draft.type}</div>
          <div style={{ fontSize: 12, color: t.color.muted, marginTop: 2 }}>{draft.subject} · {draft.muni}</div>
        </div>
        <FluentIcon name="chevron_right" size={14} style={{ color: hover ? t.color.text : t.color.dim, flexShrink: 0 }} />
      </div>
      <Progress value={parseInt(draft.status) || 0} />
    </a>
  );
}

// ─── Activity feed ──────────────────────────────────────────

function ActivityFeed({ activity }) {
  const t = window.tokens;
  return (
    <Card pad={0}>
      <div style={{ padding: '16px 18px', borderBottom: `1px solid ${t.color.hair}`, display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <div style={{ fontSize: 15, fontWeight: 600, color: t.color.text }}>Recent activity</div>
        <div style={{ fontFamily: t.font.mono, fontSize: 11, color: t.color.muted, letterSpacing: 1.2, textTransform: 'uppercase' }}>
          {activity.filter(a => !a.action).length} updates since last login
        </div>
      </div>
      <div>
        {activity.map((a, i) => (
          <div key={i} style={{
            display: 'flex', gap: 14, padding: '13px 18px',
            borderBottom: i < activity.length - 1 ? `1px solid ${t.color.hair}` : 'none',
            alignItems: 'flex-start',
          }}>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 14, color: t.color.text, lineHeight: 1.45 }}>{a.text}</div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10, fontSize: 12, color: t.color.muted, marginTop: 4 }}>
                <span style={{ fontFamily: t.font.mono }}>{a.ref}</span>
                <span style={{ width: 3, height: 3, borderRadius: 1.5, background: t.color.dim }} />
                <span>{a.muni}</span>
              </div>
            </div>
            <div style={{ fontFamily: t.font.mono, fontSize: 11, color: t.color.muted, textAlign: 'right', flexShrink: 0 }}>{a.when}</div>
          </div>
        ))}
      </div>
      <div style={{ padding: '12px 18px', borderTop: `1px solid ${t.color.hair}`, background: t.color.surfaceLo, textAlign: 'center' }}>
        <a href="#" style={{ fontSize: 13, color: t.color.action, textDecoration: 'none' }}>View all activity →</a>
      </div>
    </Card>
  );
}

const overviewRoot = ReactDOM.createRoot(document.getElementById('root'));
overviewRoot.render(<OverviewPage />);
