// DSYouHub.jsx — Meridian · Navigation 2.0 "You" hub primitives
//
//   Ported from AXIS-10 (screens/YouTab.jsx + YouAreas.jsx). "You" is no
//   longer a bottom tab — it opens from the top-right avatar and presents a
//   sheet that routes to FOUR areas: About you · Settings · Systems ·
//   Integrations.
//
//   This file owns the reusable, DS-prefixed grouped-list primitives plus
//   the landing menu sheet:
//       DSHubGroup      — titled section: header + hint, wraps rows in a card
//       DSHubRow        — tappable list row: icon · label · sublabel · value/
//                         chip/status · chevron. Supports `action` + `danger`.
//       DSHubToggleRow  — list row with a trailing DSToggle
//       DSAreaHeader    — back chevron + title for pushed area screens
//       DSYouAreaCard   — large area entry card (icon · title · desc · status)
//       DSYouMenu       — the landing sheet (profile header + 4 area cards +
//                         Sign out + version footer)
//       DSHubGlyphs (G) — the shared 24×24 stroke glyph map
//       DSGly           — the glyph wrapper component
//
//   Depends on window globals: M, DSChip, DSToggle, DSCard. References
//   window.DSYouAvatar (authored in DSNav2.jsx) for the monogram avatar when
//   available, falling back to an inline monogram tile.

// ── DSGly — shared glyph wrapper (24×24, currentColor, stroke 2) ──
function DSGly({ children, size = 18 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none"
         stroke="currentColor" strokeWidth="2"
         strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
      {children}
    </svg>
  );
}

// ── DSHubGlyphs — the `G` map ────────────────────────────────────
const DSHubGlyphs = {
  // areas
  about:    (s) => <DSGly size={s}><circle cx="12" cy="8.5" r="3.2"/><path d="M5.5 20a6.5 6.5 0 0 1 13 0"/><path d="M18.5 4.5l.6 1.7 1.7.6-1.7.6-.6 1.7-.6-1.7-1.7-.6 1.7-.6z"/></DSGly>,
  settings: (s) => <DSGly size={s}><circle cx="12" cy="12" r="3"/><path d="M12 2.5v2.2M12 19.3v2.2M21.5 12h-2.2M4.7 12H2.5M18.4 5.6l-1.6 1.6M7.2 16.8l-1.6 1.6M18.4 18.4l-1.6-1.6M7.2 7.2 5.6 5.6"/></DSGly>,
  systems:  (s) => <DSGly size={s}><rect x="3.5" y="3.5" width="7" height="7" rx="1.6"/><rect x="13.5" y="3.5" width="7" height="7" rx="1.6"/><rect x="3.5" y="13.5" width="7" height="7" rx="1.6"/><rect x="13.5" y="13.5" width="7" height="7" rx="1.6"/></DSGly>,
  plug:     (s) => <DSGly size={s}><path d="M10.5 13.5a3.5 3.5 0 0 0 5 0l2.2-2.2a3.5 3.5 0 0 0-5-5l-1 1"/><path d="M13.5 10.5a3.5 3.5 0 0 0-5 0L6.3 12.7a3.5 3.5 0 0 0 5 5l1-1"/></DSGly>,
  // rows
  bell:     (s) => <DSGly size={s}><path d="M6 8a6 6 0 0 1 12 0c0 7 3 9 3 9H3s3-2 3-9M10.3 21a1.94 1.94 0 0 0 3.4 0"/></DSGly>,
  moon:     (s) => <DSGly size={s}><path d="M20 14.5A8 8 0 0 1 9.5 4 7 7 0 1 0 20 14.5z"/></DSGly>,
  recap:    (s) => <DSGly size={s}><rect x="4" y="5" width="16" height="16" rx="2"/><path d="M4 9h16M8 3v4M16 3v4"/><path d="M9 14l2 2 4-4"/></DSGly>,
  user:     (s) => <DSGly size={s}><circle cx="12" cy="8" r="4"/><path d="M4 21a8 8 0 0 1 16 0"/></DSGly>,
  at:       (s) => <DSGly size={s}><circle cx="12" cy="12" r="4"/><path d="M16 8v5a3 3 0 0 0 6 0v-1a10 10 0 1 0-3.5 7.6"/></DSGly>,
  mail:     (s) => <DSGly size={s}><rect x="3" y="5" width="18" height="14" rx="2"/><path d="M4 7l8 6 8-6"/></DSGly>,
  phone:    (s) => <DSGly size={s}><path d="M5 4h4l2 5-2.5 1.5a11 11 0 0 0 5 5L20 18l-1 4a16 16 0 0 1-15-15z"/></DSGly>,
  key:      (s) => <DSGly size={s}><circle cx="8" cy="8" r="4"/><path d="M11 11l9 9M17 17l2-2M14 14l2.5-2.5"/></DSGly>,
  shield:   (s) => <DSGly size={s}><path d="M12 3l7 3v5c0 4.5-3 7.6-7 9-4-1.4-7-4.5-7-9V6l7-3z"/><path d="M9 12l2 2 4-4"/></DSGly>,
  devices:  (s) => <DSGly size={s}><rect x="2.5" y="4" width="13" height="9.5" rx="1.5"/><path d="M2.5 17h13"/><rect x="17.5" y="8" width="4" height="12" rx="1.5"/></DSGly>,
  lock:     (s) => <DSGly size={s}><rect x="5" y="11" width="14" height="9" rx="2"/><path d="M8 11V8a4 4 0 0 1 8 0v3"/></DSGly>,
  signout:  (s) => <DSGly size={s}><path d="M14 4h4a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2h-4"/><path d="M9 16l-4-4 4-4M5 12h10"/></DSGly>,
  sparkle:  (s) => <DSGly size={s}><path d="M12 3l1.8 5.2L19 10l-5.2 1.8L12 17l-1.8-5.2L5 10l5.2-1.8L12 3z"/></DSGly>,
  image:    (s) => <DSGly size={s}><rect x="4" y="4" width="16" height="16" rx="2"/><circle cx="9" cy="9" r="1.6"/><path d="M5 17l4.5-4.5L13 16l3-3 3 3"/></DSGly>,
  download: (s) => <DSGly size={s}><path d="M12 3v12M7.5 11l4.5 4.5L16.5 11"/><path d="M5 20h14"/></DSGly>,
  trash:    (s) => <DSGly size={s}><path d="M4 7h16M9 7V5a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2M6 7l1 13a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1l1-13"/></DSGly>,
  scale:    (s) => <DSGly size={s}><path d="M12 3v18M7 7h10M7 7l-3 6a3 3 0 0 0 6 0L7 7zM17 7l-3 6a3 3 0 0 0 6 0l-3-6zM8 21h8"/></DSGly>,
  life:     (s) => <DSGly size={s}><circle cx="12" cy="12" r="9"/><circle cx="12" cy="12" r="3.5"/><path d="M5.6 5.6l3.9 3.9M14.5 14.5l3.9 3.9M18.4 5.6l-3.9 3.9M9.5 14.5l-3.9 3.9"/></DSGly>,
  admin:    (s) => <DSGly size={s}><path d="M12 3l7 3v5c0 4.5-3 7.6-7 9-4-1.4-7-4.5-7-9V6l7-3z"/><path d="M12 8l1.2 2.6L16 11l-2 1.9.5 2.8L12 14.4 9.5 15.7l.5-2.8-2-1.9 2.8-.4z"/></DSGly>,
  heart:    (s) => <DSGly size={s}><path d="M12 20s-7-4.3-7-9.5A3.8 3.8 0 0 1 12 7a3.8 3.8 0 0 1 7 3.5C19 15.7 12 20 12 20z"/></DSGly>,
  calendar: (s) => <DSGly size={s}><rect x="4" y="5" width="16" height="16" rx="2"/><path d="M4 9h16M8 3v4M16 3v4"/></DSGly>,
  doc:      (s) => <DSGly size={s}><path d="M7 3h7l4 4v14H7z"/><path d="M14 3v4h4M9.5 13h5M9.5 16.5h5"/></DSGly>,
  chat:     (s) => <DSGly size={s}><path d="M21 15a2 2 0 0 1-2 2H8l-5 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></DSGly>,
  leaf:     (s) => <DSGly size={s}><path d="M5 20c0-9 6-15 15-15 0 9-6 15-15 15z"/><path d="M5 20C9 14 13 11 18 8"/></DSGly>,
  activity: (s) => <DSGly size={s}><path d="M3 12h4l3-9 4 18 3-9h4"/></DSGly>,
  mood:     (s) => <DSGly size={s}><circle cx="12" cy="12" r="9"/><path d="M8 14s1.5 2 4 2 4-2 4-2M9 9.5h.01M15 9.5h.01"/></DSGly>,
  today:    (s) => <DSGly size={s}><rect x="3" y="5" width="18" height="16" rx="2"/><path d="M3 10h18M8 3v4M16 3v4"/></DSGly>,
  chevron:  (s) => <DSGly size={s}><path d="M9 6l6 6-6 6"/></DSGly>,
};
const G = DSHubGlyphs;

// ─────────────────────────────────────────────────────────────────
// Grouped-list primitives
// ─────────────────────────────────────────────────────────────────

// DSHubGroup — titled section. Header (title + optional hint) above a card
// that contains the rows. Rows draw their own dividers; pass `isLast` to the
// final child to drop its hairline.
function DSHubGroup({ title, hint, children, style }) {
  return (
    <div style={{ marginBottom: 20, ...style }}>
      {title && (
        <div style={{
          display: 'flex', alignItems: 'baseline', justifyContent: 'space-between',
          padding: '0 6px', marginBottom: 8,
        }}>
          <div style={{
            font: `500 11px/1 ${M.sans}`, color: M.inkMuted,
            letterSpacing: '0.10em', textTransform: 'uppercase',
          }}>{title}</div>
          {hint && <div style={{ font: `400 11px/1 ${M.sans}`, color: M.inkFaint }}>{hint}</div>}
        </div>
      )}
      <DSCard padding={0}>{children}</DSCard>
    </div>
  );
}

// DSHubRow — the workhorse list row.
//   icon      key into DSHubGlyphs
//   label     primary text   · sublabel — secondary line
//   value     trailing text  · chip — render value in an accent DSChip
//   pos       trailing value with a green status dot
//   danger    crisis-tinted (destructive) treatment
//   action    accent treatment (call-to-action label, no chevron)
//   trailing  override the trailing slot entirely (e.g. a DSButton)
//   isLast    drop the bottom hairline
function DSHubRow({ icon, label, sublabel, value, pos, chip, danger, action, trailing, isLast, onClick }) {
  const accent = action && !danger;
  const labelColor = danger ? M.crisis : accent ? M.axis : M.ink;
  const showChevron = !action && trailing === undefined;
  return (
    <div onClick={onClick} style={{
      display: 'flex', alignItems: 'center', gap: 13,
      padding: '12px 14px', minHeight: 54,
      borderBottom: isLast ? 'none' : `1px solid ${M.ruleSoft}`,
      cursor: onClick ? 'pointer' : 'default',
    }}>
      {icon && (
        <span style={{
          width: 31, height: 31, borderRadius: 9, flexShrink: 0,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          background: danger ? '#FBEDED' : accent ? M.axisSoft : M.surfaceAlt,
          border: `1px solid ${danger ? 'rgba(180,42,42,0.18)' : accent ? 'transparent' : M.rule}`,
          color: danger ? M.crisis : accent ? M.axisDark : M.inkMuted,
        }}>
          {G[icon] ? G[icon](17) : null}
        </span>
      )}
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ font: `${accent || danger ? 500 : 400} 15px/1.25 ${M.sans}`, color: labelColor }}>{label}</div>
        {sublabel && (
          <div style={{
            font: `400 12px/1.35 ${M.sans}`, color: M.inkMuted, marginTop: 2,
            whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
          }}>{sublabel}</div>
        )}
      </div>

      {trailing !== undefined ? trailing
        : chip ? <DSChip variant="accent" style={{ padding: '3px 8px', fontSize: 11 }}>{value}</DSChip>
        : pos ? (
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, font: `500 13px/1 ${M.sans}`, color: M.success }}>
            <span style={{ width: 6, height: 6, borderRadius: 999, background: M.success }} />
            {value}
          </span>
        ) : value ? (
          <span style={{ font: `400 13px/1.3 ${M.sans}`, color: M.inkMuted, whiteSpace: 'nowrap' }}>{value}</span>
        ) : null}

      {showChevron && (
        <span style={{ flexShrink: 0, color: danger ? M.crisis : M.inkFaint, display: 'flex' }}>{G.chevron(16)}</span>
      )}
    </div>
  );
}

// DSHubToggleRow — list row with a trailing DSToggle. Self-contained state.
function DSHubToggleRow({ icon, label, sublabel, defaultOn = false, isLast }) {
  const [on, setOn] = React.useState(defaultOn);
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 13,
      padding: '12px 14px', minHeight: 54,
      borderBottom: isLast ? 'none' : `1px solid ${M.ruleSoft}`,
    }}>
      <span style={{
        width: 31, height: 31, borderRadius: 9, flexShrink: 0,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        background: M.surfaceAlt, border: `1px solid ${M.rule}`, color: M.inkMuted,
      }}>
        {G[icon] ? G[icon](17) : null}
      </span>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ font: `400 15px/1.25 ${M.sans}`, color: M.ink }}>{label}</div>
        {sublabel && <div style={{ font: `400 12px/1.35 ${M.sans}`, color: M.inkMuted, marginTop: 2 }}>{sublabel}</div>}
      </div>
      <DSToggle on={on} onChange={setOn} />
    </div>
  );
}

// DSAreaHeader — back chevron + title, used by every pushed area screen.
function DSAreaHeader({ title, onBack }) {
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 4,
      padding: '8px 12px 8px 8px', minHeight: 48, background: M.canvas, flexShrink: 0,
    }}>
      <button aria-label="Back" onClick={onBack} style={{
        width: 36, height: 36, padding: 0, background: 'transparent', border: 'none', cursor: 'pointer',
        color: M.ink, display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>
        <svg width="22" height="22" viewBox="0 0 24 24" fill="none">
          <path d="M19 12H5M11 6l-6 6 6 6" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
        </svg>
      </button>
      <div style={{ font: `500 16px/1 ${M.sans}`, color: M.ink, marginLeft: 4, letterSpacing: '-0.01em' }}>{title}</div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────
// You menu — landing sheet pieces
// ─────────────────────────────────────────────────────────────────

// DSYouAreaCard — large area entry card: icon tile · title · desc · status.
function DSYouAreaCard({ icon, title, desc, status, onClick }) {
  return (
    <DSCard padding={15} onClick={onClick || (() => {})} style={{ marginBottom: 12 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
        <span style={{
          width: 44, height: 44, borderRadius: 13, flexShrink: 0,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          background: M.axisSoft, color: M.axisDark,
        }}>{G[icon] ? G[icon](22) : null}</span>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ font: `500 16px/1.2 ${M.sans}`, color: M.ink, letterSpacing: '-0.01em' }}>{title}</div>
          <div style={{ font: `400 13px/1.4 ${M.sans}`, color: M.inkMuted, marginTop: 3 }}>{desc}</div>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexShrink: 0 }}>
          {status && (
            <span style={{ font: `400 12px/1 ${M.sans}`, color: M.inkFaint, whiteSpace: 'nowrap' }}>{status}</span>
          )}
          <span style={{ color: M.inkFaint, display: 'flex' }}>{G.chevron(18)}</span>
        </div>
      </div>
    </DSCard>
  );
}

// Monogram avatar for the profile header. Prefers window.DSYouAvatar (from
// DSNav2.jsx) when present; otherwise renders an inline ink monogram tile.
function YouProfileAvatar({ monogram = 'EH', size = 54 }) {
  if (typeof window !== 'undefined' && window.DSYouAvatar) {
    return <window.DSYouAvatar initials={monogram} size={size} />;
  }
  return (
    <div style={{
      width: size, height: size, borderRadius: 16, flexShrink: 0,
      background: M.ink, color: '#fff', font: `500 21px/1 ${M.sans}`, letterSpacing: '-0.01em',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
    }}>{monogram}</div>
  );
}

// The sheet's inner content — profile header + 4 area cards + sign out + footer.
function DSYouMenuBody({
  name = 'Eleanor Halton',
  memberSince = 'Member since March 2024',
  monogram = 'EH',
  version = 'Axis · v1.3.2',
  onSignOut,
  onArea,
}) {
  return (
    <>
      {/* profile header */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '4px 4px 18px' }}>
        <YouProfileAvatar monogram={monogram} />
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
            <span style={{ font: `500 19px/1.15 ${M.sans}`, color: M.ink, letterSpacing: '-0.015em' }}>{name}</span>
            <DSChip variant="success" dot={M.success} style={{ padding: '2px 7px', fontSize: 10.5 }}>Verified</DSChip>
          </div>
          <div style={{ font: `400 13px/1.3 ${M.sans}`, color: M.inkMuted, marginTop: 4 }}>{memberSince}</div>
        </div>
      </div>

      {/* FOUR areas, in order */}
      <DSYouAreaCard icon="about"    title="About you"    desc="Everything Axis has learned about you" status="1,284 values"  onClick={onArea && (() => onArea('about'))} />
      <DSYouAreaCard icon="settings" title="Settings"     desc="Notifications, account, privacy, legal"                       onClick={onArea && (() => onArea('settings'))} />
      <DSYouAreaCard icon="systems"  title="Systems"      desc="Manage systems and your tab slots"     status="4 active"     onClick={onArea && (() => onArea('systems'))} />
      <DSYouAreaCard icon="plug"     title="Integrations" desc="Apple Health, Calendar, and more"      status="2 connected"  onClick={onArea && (() => onArea('integrations'))} />

      <div style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        marginTop: 6, padding: '0 4px',
      }}>
        <button onClick={onSignOut} style={{
          background: 'transparent', border: 'none', padding: '6px 0', cursor: 'pointer',
          font: `500 14px/1 ${M.sans}`, color: M.crisis, display: 'inline-flex', alignItems: 'center', gap: 8,
        }}>
          <span style={{ display: 'flex', color: M.crisis }}>{G.signout(17)}</span>
          Sign out
        </button>
        <span style={{ font: `400 11.5px/1 ${M.sans}`, color: M.inkFaint }}>{version}</span>
      </div>
    </>
  );
}

// DSYouMenu — the landing sheet, presented over a dimmed scrim. Pass
// `chrome={false}` to render just the sheet card (no scrim) for embedding.
function DSYouMenu({ chrome = true, onClose, ...bodyProps }) {
  const sheet = (
    <div style={{
      background: M.surface,
      borderTopLeftRadius: 22, borderTopRightRadius: 22,
      boxShadow: chrome ? '0 -10px 40px rgba(14,18,32,0.22)' : 'none',
      display: 'flex', flexDirection: 'column', overflow: 'hidden',
      ...(chrome ? { position: 'absolute', left: 0, right: 0, bottom: 0, top: 58 }
                 : { borderRadius: 22, border: `1px solid ${M.rule}`, height: '100%' }),
    }}>
      <div style={{ display: 'flex', justifyContent: 'center', padding: '10px 0 4px', flexShrink: 0 }}>
        <span style={{ width: 38, height: 4, borderRadius: 999, background: M.rule }} />
      </div>
      <div style={{ position: 'relative', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '4px 0 8px', flexShrink: 0 }}>
        <span style={{ font: `500 15px/1 ${M.sans}`, color: M.ink }}>You</span>
        <button aria-label="Close" onClick={onClose} style={{
          position: 'absolute', right: 12, top: 0,
          width: 30, height: 30, borderRadius: 999, cursor: 'pointer',
          background: M.surfaceAlt, border: `1px solid ${M.rule}`, color: M.inkMuted,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round"><path d="M6 6l12 12M6 18L18 6"/></svg>
        </button>
      </div>
      <div style={{ flex: 1, minHeight: 0, overflowY: 'auto', padding: '8px 16px 18px' }}>
        <DSYouMenuBody {...bodyProps} />
      </div>
    </div>
  );

  if (!chrome) return sheet;

  return (
    <div style={{ position: 'relative', flex: 1, minHeight: 0, overflow: 'hidden', background: M.canvas }}>
      {/* scrim */}
      <div style={{ position: 'absolute', inset: 0, background: 'rgba(14,18,32,0.42)' }} />
      {sheet}
    </div>
  );
}

Object.assign(window, {
  DSGly, DSHubGlyphs,
  DSHubGroup, DSHubRow, DSHubToggleRow, DSAreaHeader,
  DSYouAreaCard, DSYouMenuBody, DSYouMenu,
});
