// parts.jsx — shared UI primitives for the live PWA.

const T = window.THEME;

// ── Icons (line set) ─────────────────────────────────────────────
const Icon = ({ d, size = 18, stroke = 'currentColor', strokeWidth = 1.6, children, vb = '0 0 24 24', style }) => (
  <svg width={size} height={size} viewBox={vb} fill="none" stroke={stroke}
       strokeWidth={strokeWidth} strokeLinecap="round" strokeLinejoin="round" style={style}>
    {d ? <path d={d}/> : children}
  </svg>
);

const Icons = {
  plus:    (p) => <Icon {...p} d="M12 5v14M5 12h14"/>,
  home:    (p) => <Icon {...p} d="M3 11l9-7 9 7v9a2 2 0 0 1-2 2h-4v-6h-6v6H5a2 2 0 0 1-2-2v-9z"/>,
  list:    (p) => <Icon {...p}><path d="M8 6h13M8 12h13M8 18h13"/><circle cx="4" cy="6" r="1.2"/><circle cx="4" cy="12" r="1.2"/><circle cx="4" cy="18" r="1.2"/></Icon>,
  chart:   (p) => <Icon {...p}><path d="M3 21h18"/><path d="M6 17v-5M11 17V8M16 17v-3M21 17v-7"/></Icon>,
  calendar:(p) => <Icon {...p}><rect x="3.5" y="5" width="17" height="16" rx="2"/><path d="M3.5 10h17M8 3v4M16 3v4"/></Icon>,
  share:   (p) => <Icon {...p}><path d="M12 15V3M8 7l4-4 4 4"/><path d="M5 12v7a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2v-7"/></Icon>,
  gear:    (p) => <Icon {...p}><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.7 1.7 0 0 0 .3 1.8l.1.1a2 2 0 1 1-2.8 2.8l-.1-.1a1.7 1.7 0 0 0-1.8-.3 1.7 1.7 0 0 0-1 1.5V21a2 2 0 1 1-4 0v-.1a1.7 1.7 0 0 0-1.1-1.6 1.7 1.7 0 0 0-1.8.3l-.1.1a2 2 0 1 1-2.8-2.8l.1-.1a1.7 1.7 0 0 0 .3-1.8 1.7 1.7 0 0 0-1.5-1H3a2 2 0 1 1 0-4h.1a1.7 1.7 0 0 0 1.6-1.1 1.7 1.7 0 0 0-.3-1.8l-.1-.1a2 2 0 1 1 2.8-2.8l.1.1a1.7 1.7 0 0 0 1.8.3H9A1.7 1.7 0 0 0 10 3.1V3a2 2 0 1 1 4 0v.1A1.7 1.7 0 0 0 15 4.7a1.7 1.7 0 0 0 1.8-.3l.1-.1a2 2 0 1 1 2.8 2.8l-.1.1a1.7 1.7 0 0 0-.3 1.8V9a1.7 1.7 0 0 0 1.5 1H21a2 2 0 1 1 0 4h-.1a1.7 1.7 0 0 0-1.5 1z"/></Icon>,
  sun:     (p) => <Icon {...p}><circle cx="12" cy="12" r="4"/><path d="M12 2v2M12 20v2M4.9 4.9l1.4 1.4M17.7 17.7l1.4 1.4M2 12h2M20 12h2M4.9 19.1l1.4-1.4M17.7 6.3l1.4-1.4"/></Icon>,
  cloud:   (p) => <Icon {...p} d="M7 18a4 4 0 1 1 1-7.9A5 5 0 0 1 18 11a3.5 3.5 0 0 1 0 7H7z"/>,
  drop:    (p) => <Icon {...p} d="M12 3s6 7 6 11a6 6 0 1 1-12 0c0-4 6-11 6-11z"/>,
  leaf:    (p) => <Icon {...p}><path d="M4 20c0-10 7-16 16-16-.4 9.6-6.4 16-16 16z"/><path d="M4 20c4-4 8-7 13-9"/></Icon>,
  wind:    (p) => <Icon {...p} d="M3 8h10a3 3 0 1 0-3-3M3 12h15a3 3 0 1 1-3 3M3 16h8"/>,
  pill:    (p) => <Icon {...p}><rect x="2" y="9" width="20" height="6" rx="3" transform="rotate(-30 12 12)"/><path d="M14.1 4.9 9 19.1"/></Icon>,
  clock:   (p) => <Icon {...p}><circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/></Icon>,
  pin:     (p) => <Icon {...p}><path d="M12 22s8-7.5 8-13a8 8 0 1 0-16 0c0 5.5 8 13 8 13z"/><circle cx="12" cy="9" r="2.6"/></Icon>,
  check:   (p) => <Icon {...p} d="M4 12l5 5L20 6"/>,
  x:       (p) => <Icon {...p} d="M6 6l12 12M18 6L6 18"/>,
  chev:    (p) => <Icon {...p} d="M9 6l6 6-6 6"/>,
  back:    (p) => <Icon {...p} d="M15 6l-6 6 6 6"/>,
  arrow:   (p) => <Icon {...p} d="M5 12h14M13 6l6 6-6 6"/>,
  heart:   (p) => <Icon {...p} d="M12 21s-7-4.5-9.5-9A5.5 5.5 0 0 1 12 6a5.5 5.5 0 0 1 9.5 6c-2.5 4.5-9.5 9-9.5 9z"/>,
  spark:   (p) => <Icon {...p}><path d="M12 3v4M12 17v4M3 12h4M17 12h4M5.6 5.6l2.8 2.8M15.6 15.6l2.8 2.8M5.6 18.4l2.8-2.8M15.6 8.4l2.8-2.8"/></Icon>,
  sync:    (p) => <Icon {...p}><path d="M3 12a9 9 0 0 1 15.5-6.2L21 8M21 3v5h-5M21 12a9 9 0 0 1-15.5 6.2L3 16M3 21v-5h5"/></Icon>,
  bolt:    (p) => <Icon {...p} d="M13 2L4 14h7l-1 8 9-12h-7l1-8z"/>,
  doc:     (p) => <Icon {...p}><path d="M6 3h8l5 5v13a1 1 0 0 1-1 1H6a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1z"/><path d="M14 3v5h5M8 13h8M8 17h6"/></Icon>,
  health:  (p) => <Icon {...p} d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78L12 21l8.84-8.61a5.5 5.5 0 0 0 0-7.78z"/>,
  download:(p) => <Icon {...p} d="M12 3v12m0 0l-4-4m4 4l4-4M5 21h14"/>,
};

// ── Text ──────────────────────────────────────────────────────────
function H1({ children, style }) {
  return <div style={{ fontFamily: T.fontDisplay, fontSize: 30, fontWeight: 700, letterSpacing: -0.7, lineHeight: 1.08, color: T.ink, ...style }}>{children}</div>;
}
function H2({ children, style }) {
  return <div style={{ fontFamily: T.fontDisplay, fontSize: 20, fontWeight: 600, letterSpacing: -0.3, lineHeight: 1.15, color: T.ink, ...style }}>{children}</div>;
}
function Label({ children, style }) {
  return <div style={{ fontFamily: T.font, fontSize: 11, fontWeight: 600, letterSpacing: 0.6, textTransform: 'uppercase', color: T.muted, ...style }}>{children}</div>;
}
function Muted({ children, size = 13, style }) {
  return <div style={{ fontFamily: T.font, fontSize: size, color: T.muted, lineHeight: 1.4, ...style }}>{children}</div>;
}

// ── Card ──────────────────────────────────────────────────────────
function Card({ children, style, pad = 16 }) {
  return (
    <div style={{
      background: T.surface, borderRadius: 16, padding: pad,
      boxShadow: `0 1px 1px rgba(16,20,24,0.03), 0 0 0 1px ${T.hairline}`,
      ...style,
    }}>{children}</div>
  );
}

// ── Chip ──────────────────────────────────────────────────────────
function Chip({ active, children, onClick, size = 'md', style }) {
  const sizes = { sm: { h: 28, fs: 12, px: 10 }, md: { h: 34, fs: 13, px: 13 } };
  const s = sizes[size];
  return (
    <button onClick={onClick} style={{
      height: s.h, padding: `0 ${s.px}px`, borderRadius: 999,
      background: active ? T.accent : 'transparent',
      color: active ? '#fff' : T.inkSoft,
      border: '1px solid ' + (active ? T.accent : T.hairline),
      fontFamily: T.font, fontSize: s.fs, fontWeight: active ? 600 : 500,
      cursor: 'pointer', whiteSpace: 'nowrap',
      display: 'inline-flex', alignItems: 'center', gap: 6,
      ...style,
    }}>{children}</button>
  );
}

// ── Severity badge ────────────────────────────────────────────────
function SeverityBadge({ level, size = 'md' }) {
  const labels = { mild: 'Mild', moderate: 'Moderate', severe: 'Severe', debilitating: 'Debilitating' };
  const c = T.sev[level] || T.sev.moderate;
  const sizes = { sm: { h: 22, fs: 11, px: 9, dot: 5 }, md: { h: 26, fs: 12, px: 10, dot: 6 } };
  const s = sizes[size];
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 6,
      height: s.h, padding: `0 ${s.px}px`, borderRadius: 999,
      background: c.bg, color: c.ink,
      fontFamily: T.font, fontSize: s.fs, fontWeight: 600, letterSpacing: 0.1,
    }}>
      <span style={{ width: s.dot, height: s.dot, borderRadius: '50%', background: c.dot }}/>
      {labels[level] || level}
    </span>
  );
}

// ── Switch ────────────────────────────────────────────────────────
function Switch({ on, onChange }) {
  return (
    <div onClick={() => onChange && onChange(!on)} style={{
      width: 38, height: 22, borderRadius: 999, cursor: 'pointer',
      background: on ? T.accent : T.subtle,
      position: 'relative', transition: 'background 0.18s',
    }}>
      <div style={{
        position: 'absolute', top: 2, left: on ? 18 : 2,
        width: 18, height: 18, borderRadius: '50%', background: '#fff',
        boxShadow: '0 1px 2px rgba(0,0,0,0.2)', transition: 'left 0.18s',
      }}/>
    </div>
  );
}

// ── Tab bar ───────────────────────────────────────────────────────
const TAB_LIST = [
  { id: 'home',     label: 'Today',    icon: 'home' },
  { id: 'history',  label: 'History',  icon: 'list' },
  { id: 'log',      label: 'Log',      icon: 'plus', primary: true },
  { id: 'patterns', label: 'Patterns', icon: 'chart' },
  { id: 'calendar', label: 'Calendar', icon: 'calendar' },
];

function TabBar({ active, onChange, readOnly }) {
  return (
    <div style={{
      position: 'fixed', left: 0, right: 0, bottom: 0, zIndex: 50,
      paddingBottom: 'max(env(safe-area-inset-bottom), 18px)', paddingTop: 8,
      background: T.surface, borderTop: '1px solid ' + T.hairline,
      display: 'flex', justifyContent: 'space-around', alignItems: 'flex-end',
      fontFamily: T.font,
    }}>
      {TAB_LIST.filter((t) => !(readOnly && t.primary)).map(tab => {
        const I = Icons[tab.icon];
        const isActive = tab.id === active;
        if (tab.primary) {
          return (
            <button key={tab.id} onClick={() => onChange(tab.id)} style={{
              background: 'none', border: 'none', cursor: 'pointer',
              display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4,
              transform: 'translateY(-12px)', padding: 0,
            }}>
              <div style={{
                width: 52, height: 52, borderRadius: 999,
                background: isActive ? T.accentInk : T.accent, color: '#fff',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                boxShadow: `0 6px 16px ${T.accent}55, 0 2px 4px rgba(0,0,0,0.08)`,
              }}>
                <I size={24} strokeWidth={2.2}/>
              </div>
              <div style={{ fontSize: 10, fontWeight: 600, color: isActive ? T.accentInk : T.muted }}>{tab.label}</div>
            </button>
          );
        }
        return (
          <button key={tab.id} onClick={() => onChange(tab.id)} style={{
            background: 'none', border: 'none', cursor: 'pointer',
            display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 3,
            color: isActive ? T.accentInk : T.muted, padding: '4px 8px',
            minWidth: 52,
          }}>
            <I size={22} strokeWidth={isActive ? 2.1 : 1.7}/>
            <div style={{ fontSize: 10.5, fontWeight: isActive ? 600 : 500 }}>{tab.label}</div>
          </button>
        );
      })}
    </div>
  );
}

// ── Page chrome ───────────────────────────────────────────────────
function Page({ title, right, children }) {
  return (
    <div style={{
      minHeight: '100vh',
      paddingTop: 'max(env(safe-area-inset-top), 44px)',
      paddingBottom: 'calc(env(safe-area-inset-bottom, 0px) + 110px)',
      background: T.bg, color: T.ink, fontFamily: T.font,
    }}>
      {title && (
        <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', padding: '6px 18px 8px' }}>
          <H1>{title}</H1>
          {right}
        </div>
      )}
      <div style={{ padding: '0 18px' }}>{children}</div>
    </div>
  );
}

// ── Bottom sheet ──────────────────────────────────────────────────
function Sheet({ open, onClose, children, height = 'auto' }) {
  if (!open) return null;
  return (
    <div onClick={onClose} style={{
      position: 'fixed', inset: 0, zIndex: 100,
      background: 'rgba(16,20,24,0.32)',
      display: 'flex', alignItems: 'flex-end', justifyContent: 'center',
    }}>
      <div onClick={(e) => e.stopPropagation()} style={{
        background: T.surface, borderTopLeftRadius: 24, borderTopRightRadius: 24,
        padding: '14px 20px calc(env(safe-area-inset-bottom, 0px) + 24px)',
        width: '100%', maxWidth: 480, maxHeight: '88vh', overflowY: 'auto',
        boxShadow: '0 -20px 60px rgba(0,0,0,0.18)',
        height,
      }}>
        <div style={{ width: 36, height: 4, borderRadius: 2, background: T.subtle, margin: '0 auto 14px' }}/>
        {children}
      </div>
    </div>
  );
}

// ── Buttons ───────────────────────────────────────────────────────
function PrimaryButton({ children, onClick, disabled, style }) {
  return (
    <button onClick={onClick} disabled={disabled} style={{
      width: '100%', height: 48, borderRadius: 12, border: 'none',
      background: disabled ? T.subtle : T.accent,
      color: disabled ? T.muted : '#fff',
      fontFamily: T.font, fontSize: 15, fontWeight: 600,
      cursor: disabled ? 'not-allowed' : 'pointer',
      ...style,
    }}>{children}</button>
  );
}

function GhostButton({ children, onClick, style }) {
  return (
    <button onClick={onClick} style={{
      height: 40, padding: '0 14px', borderRadius: 999,
      background: 'transparent', color: T.inkSoft,
      border: '1px solid ' + T.hairline,
      fontFamily: T.font, fontSize: 13, fontWeight: 500, cursor: 'pointer',
      ...style,
    }}>{children}</button>
  );
}

// ── Mini bars ─────────────────────────────────────────────────────
function MiniBars({ values, w = 200, h = 60, color }) {
  const max = Math.max(...values, 1);
  const gap = 3;
  const bw = (w - gap * (values.length - 1)) / Math.max(values.length, 1);
  return (
    <svg width={w} height={h}>
      {values.map((v, i) => {
        const bh = (v / max) * (h - 2);
        return <rect key={i} x={i * (bw + gap)} y={h - bh} width={bw} height={bh} rx={2} fill={color || T.accent} opacity={0.85}/>;
      })}
    </svg>
  );
}

// ── Viewing-as banner ─────────────────────────────────────────────
function ViewingAsBanner({ ownerName, ownerEmail, onSwitchBack }) {
  return (
    <div style={{
      position: 'fixed', top: 0, left: 0, right: 0, zIndex: 200,
      padding: 'max(env(safe-area-inset-top), 8px) 14px 8px',
      background: T.accent, color: '#fff',
      fontFamily: T.font, fontSize: 12, fontWeight: 500,
      display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8,
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, minWidth: 0 }}>
        <span style={{
          fontSize: 10, fontWeight: 700, letterSpacing: 0.5, textTransform: 'uppercase',
          background: 'rgba(255,255,255,0.22)', padding: '2px 6px', borderRadius: 4,
        }}>View only</span>
        <span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
          Viewing {ownerName || ownerEmail}'s data
        </span>
      </div>
      <button onClick={onSwitchBack} style={{
        background: 'rgba(255,255,255,0.18)', color: '#fff', border: 'none',
        borderRadius: 999, height: 24, padding: '0 10px',
        fontFamily: T.font, fontSize: 11, fontWeight: 600, cursor: 'pointer',
      }}>Switch back</button>
    </div>
  );
}

// ── "Viewing as" picker ───────────────────────────────────────────
function ViewAsPicker({ acceptedShares, currentViewAs, onPick }) {
  const [open, setOpen] = React.useState(false);
  if (!acceptedShares || acceptedShares.length === 0) return null;
  const label = currentViewAs ? (currentViewAs.name || currentViewAs.email) : 'Me';
  return (
    <>
      <button onClick={() => setOpen(true)} style={{
        background: 'rgba(255,255,255,0.85)', backdropFilter: 'blur(8px)',
        border: '1px solid rgba(16,20,24,0.06)', color: T.inkSoft,
        borderRadius: 999, height: 32, padding: '0 12px',
        fontFamily: T.font, fontSize: 12, fontWeight: 600,
        display: 'inline-flex', alignItems: 'center', gap: 6, cursor: 'pointer',
      }}>
        <span style={{ opacity: 0.7 }}>Viewing as</span>
        <span>{label}</span>
        <Icons.chev size={12}/>
      </button>
      <Sheet open={open} onClose={() => setOpen(false)}>
        <div style={{ fontFamily: T.font, fontSize: 14, fontWeight: 600, marginBottom: 10 }}>Viewing as</div>
        <PickRow label="Me" sublabel="Your own data" selected={!currentViewAs}
          onClick={() => { onPick(null); setOpen(false); }}/>
        {acceptedShares.map((s) => (
          <PickRow key={s.id}
            label={s.ownerName || s.ownerEmail}
            sublabel={s.ownerEmail}
            selected={currentViewAs?.email === s.ownerEmail}
            onClick={() => { onPick({ email: s.ownerEmail, name: s.ownerName || s.ownerEmail }); setOpen(false); }}/>
        ))}
      </Sheet>
    </>
  );
}

function PickRow({ label, sublabel, selected, onClick }) {
  return (
    <div onClick={onClick} style={{
      display: 'flex', alignItems: 'center', gap: 12, padding: '12px 4px', cursor: 'pointer',
      borderBottom: '1px solid ' + T.hairline,
    }}>
      <div style={{
        width: 22, height: 22, borderRadius: 999,
        border: '2px solid ' + (selected ? T.accent : T.subtle),
        background: selected ? T.accent : 'transparent',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>{selected && <Icons.check size={12} stroke="#fff" strokeWidth={2.4}/>}</div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontFamily: T.font, fontSize: 14, fontWeight: 500, color: T.ink }}>{label}</div>
        {sublabel && <div style={{ fontSize: 11.5, color: T.muted, marginTop: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{sublabel}</div>}
      </div>
    </div>
  );
}

Object.assign(window, {
  T, Icons, H1, H2, Label, Muted, Card, Chip, SeverityBadge, Switch,
  TabBar, Page, Sheet, PrimaryButton, GhostButton, MiniBars, TAB_LIST,
  ViewingAsBanner, ViewAsPicker,
});
