/* Mobile foundation primitives — used by foundation-sections.jsx.
   Reuses TK_DARK / TK_LIGHT / SUBJECTS from polish/tokens.js. */

const { useState: fUseState } = React;

/* ─── Lucide icon ─── */
function MI({ name, size = 16, color = 'currentColor', strokeWidth = 2, fill = 'none', style }) {
  const icons = window.lucide && window.lucide.icons;
  if (!icons) return null;
  const pascal = name.split('-').map(s => s[0].toUpperCase() + s.slice(1)).join('');
  const data = icons[pascal] || icons[name];
  if (!data) return null;
  const children = Array.isArray(data) ? (data[2] || []) : (data.children || []);
  const html = children.map(c => {
    if (!Array.isArray(c)) return '';
    const [tag, a] = c;
    if (!tag || !a) return '';
    const attrs = Object.entries(a).map(([k, v]) => `${k}="${v}"`).join(' ');
    return `<${tag} ${attrs}/>`;
  }).join('');
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill={fill}
      stroke={color} strokeWidth={strokeWidth} strokeLinecap="round" strokeLinejoin="round"
      style={{ flexShrink: 0, ...(style || {}) }}
      dangerouslySetInnerHTML={{ __html: html }} />
  );
}

/* ─── PhoneShell — 390×844 iPhone-14 reference frame ─── */
function PhoneShell({ t, height = 844, width = 390, children, label, style }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 10, ...(style || {}) }}>
      {label && (
        <div style={{
          fontSize: 11, fontWeight: 800, color: t.fgMute,
          letterSpacing: 0.6, textTransform: 'uppercase',
        }}>{label}</div>
      )}
      <div style={{
        width, height, borderRadius: 44, overflow: 'hidden',
        background: t.card, border: `1px solid ${t.border}`,
        boxShadow: t.shadowElev,
        display: 'flex', flexDirection: 'column',
        position: 'relative', isolation: 'isolate',
      }}>
        {children}
      </div>
    </div>
  );
}

/* ─── StatusBar — 24h iOS-style ─── */
function StatusBar({ t }) {
  return (
    <div style={{
      height: 24, padding: '0 22px',
      display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      flexShrink: 0, color: t.fg,
      fontFamily: 'Nunito', fontWeight: 700, fontSize: 12,
    }}>
      <span style={{ letterSpacing: 0.2 }}>9:41</span>
      <div style={{ display: 'flex', alignItems: 'center', gap: 5 }}>
        <MI name="signal" size={12} color={t.fg} strokeWidth={2.4} />
        <MI name="wifi" size={12} color={t.fg} strokeWidth={2.4} />
        <MI name="battery-full" size={14} color={t.fg} strokeWidth={2.2} />
      </div>
    </div>
  );
}

/* ─── MobileTopbar — Plannen with subtitle + pills ─── */
function MobileTopbar({ t, title = 'Plannen', subtitle, bell = 'on', bellAlert = false }) {
  return (
    <header style={{
      background: t.topbar, borderBottom: `1px solid ${t.border}`,
      padding: '8px 16px 10px', display: 'flex', alignItems: 'center',
      gap: 10, flexShrink: 0, minHeight: 56, boxSizing: 'border-box',
    }}>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontFamily: 'Fredoka One', fontSize: 20, color: t.fg, lineHeight: 1.15, letterSpacing: '-0.01em' }}>{title}</div>
        {subtitle && <div style={{ fontSize: 11.5, color: t.fgDim, fontWeight: 600, marginTop: 1, lineHeight: 1.3 }}>{subtitle}</div>}
      </div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 6, flexShrink: 0 }}>
        <SnapsPillSm t={t} count={240} />
        <StreakPillSm t={t} count={5} />
        {bell !== 'off' && (
          <button style={{
            width: 32, height: 32, borderRadius: 9, background: 'transparent',
            border: 'none', color: t.fgDim,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            cursor: 'pointer', position: 'relative',
          }}>
            <MI name="bell" size={18} color={t.fgDim} />
            {bellAlert && (
              <span style={{
                position: 'absolute', top: 5, right: 5,
                width: 7, height: 7, borderRadius: 999,
                background: t.red, border: `1.5px solid ${t.topbar}`,
              }} />
            )}
          </button>
        )}
      </div>
    </header>
  );
}

function SnapsPillSm({ t, count }) {
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 3, height: 22,
      padding: '0 8px', borderRadius: 999,
      background: t.goldDim, color: t.gold,
      border: `1px solid ${hexToRgba(t.gold, 0.30)}`,
      fontFamily: 'Nunito', fontWeight: 800, fontSize: 11.5, lineHeight: 1,
    }}>
      <MI name="zap" size={10} fill="currentColor" color={t.gold} strokeWidth={0} />
      {count}
    </span>
  );
}

function StreakPillSm({ t, count }) {
  const orange = t.mode === 'dark' ? '#F97316' : '#C2410C';
  const orangeBg = t.mode === 'dark' ? 'rgba(249,115,22,0.14)' : 'rgba(234,88,12,0.10)';
  const orangeBd = t.mode === 'dark' ? 'rgba(249,115,22,0.28)' : 'rgba(234,88,12,0.30)';
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 3, height: 22,
      padding: '0 8px', borderRadius: 999,
      background: orangeBg, color: orange, border: `1px solid ${orangeBd}`,
      fontFamily: 'Nunito', fontWeight: 800, fontSize: 11.5, lineHeight: 1,
    }}>
      <span style={{ fontSize: 10 }}>🔥</span>{count}×
    </span>
  );
}

/* ─── MobileBottomNav — 5 tabs, matches SnapSnel web sidebar ─── */
function MobileBottomNav({ t, active = 'plannen' }) {
  const items = [
    { k: 'dashboard', icon: 'layout-grid', label: 'Dashboard' },
    { k: 'leren', icon: 'graduation-cap', label: 'Leren' },
    { k: 'oefenen', icon: 'target', label: 'Oefenen' },
    { k: 'plannen', icon: 'calendar', label: 'Plannen' },
    { k: 'profiel', icon: 'user', label: 'Profiel' },
  ];
  return (
    <nav style={{
      background: t.topbar, borderTop: `1px solid ${t.border}`,
      height: 80, /* 64 content + 16 safe-area */
      padding: '8px 6px 16px', display: 'flex',
      alignItems: 'stretch', justifyContent: 'space-between',
      flexShrink: 0,
    }}>
      {items.map(it => {
        const on = it.k === active;
        const color = on ? t.primary : t.fgFaint;
        return (
          <div key={it.k} style={{
            flex: 1, display: 'flex', flexDirection: 'column',
            alignItems: 'center', justifyContent: 'center', gap: 4,
            padding: '6px 4px', borderRadius: 16, /* radius-xl */
            background: on ? t.primaryDim : 'transparent',
          }}>
            <MI name={it.icon} size={24} color={color} strokeWidth={on ? 2.4 : 2} />
            <span style={{
              fontSize: 11, fontWeight: 800,
              color, letterSpacing: 0.2, lineHeight: 1,
            }}>{it.label}</span>
          </div>
        );
      })}
    </nav>
  );
}

function PulseTabIcon({ t, active }) {
  // Mini-Pulse glyph — round body + lightning ear-tuft
  const fill = active ? t.primary : t.fgFaint;
  return (
    <svg width="22" height="22" viewBox="0 0 24 24" fill="none" style={{ flexShrink: 0 }}>
      <ellipse cx="12" cy="13.5" rx="7.2" ry="6.5" fill={fill} opacity={active ? 1 : 0.85} />
      <path d="M14 4 L10.5 10.5 L13 10.5 L11.5 14.5 L15.5 8 L13 8 Z" fill={fill} />
      <circle cx="9.5" cy="13" r="1.1" fill={t.card} />
      <circle cx="14.2" cy="13" r="1.1" fill={t.card} />
    </svg>
  );
}

/* ─── DotGrid — placeholder fill for body ─── */
function DotGrid({ t }) {
  const dot = t.mode === 'dark' ? 'rgba(148,163,184,0.18)' : 'rgba(15,23,42,0.10)';
  return (
    <div style={{
      flex: 1, background: t.bgApp,
      backgroundImage: `radial-gradient(${dot} 1px, transparent 1px)`,
      backgroundSize: '12px 12px', backgroundPosition: '0 0',
    }} />
  );
}

/* ─── Pulse mascot SVG (file-based) ─── */
function PulseMascotImg({ size = 46, mood = 'happy', style }) {
  const map = { happy: 'happy', thinking: 'thinking', encouraging: 'celebrating', observing: 'idle' };
  const file = map[mood] || 'happy';
  const w = Math.round(size * (200 / 280));
  return (
    <img src={`polish-mobile/assets/pulse-${file}.svg`} alt="" width={w} height={size}
      style={{ display: 'block', flexShrink: 0, ...(style || {}) }} />
  );
}

/* ─── Buttons (mobile sizes) ─── */
function Btn({ t, variant = 'primary', size = 'md', state = 'default', icon, iconRight, full = false, children }) {
  const sizes = {
    sm: { h: 32, fs: 12, pad: '0 12px', radius: 10, ic: 14 },
    md: { h: 40, fs: 14, pad: '0 16px', radius: 11, ic: 16 },
    lg: { h: 48, fs: 16, pad: '0 20px', radius: 12, ic: 18 },
  }[size];
  const variants = {
    primary: { bg: t.primary, fg: '#FFFFFF', bd: t.primary, sh: t.shadowCard },
    secondary: { bg: t.card, fg: t.fg, bd: t.border, sh: 'none' },
    ghost: { bg: 'transparent', fg: t.primary, bd: 'transparent', sh: 'none' },
    destructive: { bg: t.red, fg: '#FFFFFF', bd: t.red, sh: t.shadowCard },
    gold: { bg: t.gold, fg: '#FFFFFF', bd: t.gold, sh: t.shadowCard },
  }[variant];
  const transform = state === 'active' ? 'scale(0.97)' : 'none';
  const opacity = state === 'disabled' ? 0.45 : state === 'active' ? 0.92 : 1;
  return (
    <button disabled={state === 'disabled'} style={{
      height: sizes.h, padding: sizes.pad, borderRadius: sizes.radius,
      background: variants.bg, color: variants.fg,
      border: `1px solid ${variants.bd}`,
      boxShadow: variants.sh,
      fontFamily: 'Nunito', fontWeight: 800, fontSize: sizes.fs, letterSpacing: 0.2,
      display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 6,
      cursor: state === 'disabled' ? 'not-allowed' : 'pointer',
      transform, opacity, width: full ? '100%' : 'auto',
      whiteSpace: 'nowrap',
    }}>
      {icon && <MI name={icon} size={sizes.ic} color={variants.fg} strokeWidth={2.4} />}
      {children}
      {iconRight && <MI name={iconRight} size={sizes.ic} color={variants.fg} strokeWidth={2.4} />}
    </button>
  );
}

/* ─── Bottom-sheet (rendered over a phone-shell content) ─── */
function BottomSheet({ t, height = 'medium', title, children, footer, onClose }) {
  const heights = { small: 0.40, medium: 0.65, full: 1 };
  const ratio = heights[height] || 0.65;
  return (
    <div style={{
      position: 'absolute', inset: 0, display: 'flex', flexDirection: 'column',
      justifyContent: 'flex-end', zIndex: 5,
    }}>
      <div style={{ position: 'absolute', inset: 0, background: t.scrim }} />
      <div style={{
        position: 'relative', height: height === 'full' ? `calc(100% - 24px)` : `${ratio * 100}%`,
        background: t.card,
        borderTopLeftRadius: 24, borderTopRightRadius: 24,
        boxShadow: '0 -8px 32px rgba(0,0,0,0.18)',
        display: 'flex', flexDirection: 'column',
        overflow: 'hidden',
      }}>
        {/* Drag-handle */}
        <div style={{ display: 'flex', justifyContent: 'center', paddingTop: 8 }}>
          <div style={{ width: 36, height: 4, borderRadius: 999, background: t.fgFaint, opacity: 0.55 }} />
        </div>
        {/* Header */}
        <div style={{
          padding: '12px 18px 10px',
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        }}>
          <div style={{ fontFamily: 'Fredoka One', fontSize: 18, color: t.fg, letterSpacing: '-0.01em' }}>{title}</div>
          <button style={{
            width: 28, height: 28, borderRadius: 8,
            background: 'transparent', border: 'none', color: t.fgDim,
            display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer',
          }}><MI name="x" size={20} color={t.fgDim} /></button>
        </div>
        <div style={{ flex: 1, overflow: 'auto', padding: '4px 18px 16px' }}>
          {children}
        </div>
        {footer && (
          <div style={{
            padding: '10px 16px 16px', borderTop: `1px solid ${t.border}`,
            background: t.card, display: 'flex', gap: 8,
          }}>{footer}</div>
        )}
      </div>
    </div>
  );
}

/* ─── Skeleton placeholder rows for sheets ─── */
function SkeletonRow({ t, width = '100%', height = 14 }) {
  return (
    <div style={{
      width, height, borderRadius: 6,
      background: t.cardSunken, border: `1px solid ${t.border}`, opacity: 0.7,
    }} />
  );
}

/* ─── Banner — flexible Pulse-led card ─── */
function Banner({ t, accent, accentRgb, mood, icon, label, title, body, ctas, dismissible }) {
  // accent is a hex; accentRgb is "r,g,b" tuple for color-mix-style usage
  const aBg = `rgba(${accentRgb}, 0.08)`;
  const aBd = `rgba(${accentRgb}, 0.30)`;
  return (
    <div style={{
      background: aBg, border: `1px solid ${aBd}`,
      borderRadius: 16, padding: 16,
      position: 'relative', overflow: 'hidden',
    }}>
      <div style={{
        position: 'absolute', top: 0, left: 0, right: 0, height: 3,
        background: `linear-gradient(90deg, ${accent}, transparent)`,
      }} />
      {dismissible && (
        <button style={{
          position: 'absolute', top: 10, right: 10,
          width: 24, height: 24, borderRadius: 6,
          background: 'transparent', border: 'none', color: t.fgDim,
          display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer',
        }}><MI name="x" size={16} color={t.fgDim} /></button>
      )}
      <div style={{ display: 'flex', gap: 12, alignItems: 'flex-start' }}>
        {mood ? (
          <PulseMascotImg size={52} mood={mood} style={{ marginTop: 2 }} />
        ) : icon ? (
          <div style={{
            width: 44, height: 44, borderRadius: 12,
            background: `rgba(${accentRgb}, 0.14)`,
            border: `1px solid ${aBd}`,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            flexShrink: 0,
          }}><MI name={icon} size={22} color={accent} strokeWidth={2.2} /></div>
        ) : null}
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{
            fontSize: 10, fontWeight: 800, letterSpacing: 0.8,
            textTransform: 'uppercase', color: accent, marginBottom: 4,
          }}>{label}</div>
          <div style={{
            fontFamily: 'Fredoka One', fontSize: 18, color: t.fg,
            lineHeight: 1.25, letterSpacing: '-0.01em', marginBottom: 5,
          }}>{title}</div>
          <div style={{ fontSize: 12.5, fontWeight: 500, color: t.fgDim, lineHeight: 1.5 }}>{body}</div>
          {ctas && (
            <div style={{ marginTop: 12, display: 'flex', flexDirection: 'column', gap: 6 }}>
              {ctas}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

/* ─── EmptyCard — dashed-border placeholder with copy + CTAs ─── */
function EmptyCard({ t, icon, iconColor, title, body, ctas }) {
  return (
    <div style={{
      background: t.card, border: `2px dashed ${t.border}`, borderRadius: 16,
      padding: 24, minHeight: 200,
      display: 'flex', flexDirection: 'column', alignItems: 'center',
      justifyContent: 'center', textAlign: 'center', gap: 8,
    }}>
      <div style={{
        width: 52, height: 52, borderRadius: 14,
        background: t.cardSunken, border: `1px solid ${t.border}`,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        marginBottom: 4,
      }}>
        <MI name={icon} size={26} color={iconColor || t.fgMute} strokeWidth={2.2} />
      </div>
      <div style={{ fontFamily: 'Fredoka One', fontSize: 17, color: t.fg, letterSpacing: '-0.01em', lineHeight: 1.25 }}>{title}</div>
      <div style={{ fontSize: 12, color: t.fgDim, fontWeight: 500, lineHeight: 1.5, maxWidth: 280 }}>{body}</div>
      {ctas && (
        <div style={{ marginTop: 10, display: 'flex', flexWrap: 'wrap', gap: 6, justifyContent: 'center' }}>
          {ctas}
        </div>
      )}
    </div>
  );
}

/* ─── FAB — floating action button ─── */
function Fab({ t, state = 'default' }) {
  const transform = state === 'active' ? 'scale(0.94)' : 'none';
  const sh = state === 'active'
    ? `0 12px 36px ${hexToRgba(t.primary, 0.45)}, 0 0 0 8px ${hexToRgba(t.primary, 0.10)}`
    : `0 8px 24px ${hexToRgba(t.primary, 0.35)}`;
  return (
    <button style={{
      width: 56, height: 56, borderRadius: 999,
      background: t.primary, color: '#FFFFFF',
      border: 'none', boxShadow: sh,
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      cursor: 'pointer', transform,
    }}><MI name="plus" size={26} color="#FFFFFF" strokeWidth={2.6} /></button>
  );
}

/* ─── Section header ─── */
function SectionHeader({ t, title, caption }) {
  return (
    <div style={{ marginBottom: 24 }}>
      <h2 style={{
        margin: 0, fontFamily: 'Fredoka One', fontSize: 28, color: t.fg,
        letterSpacing: '-0.01em', lineHeight: 1.15,
        paddingBottom: 8, borderBottom: `1px solid ${t.border}`,
      }}>{title}</h2>
      {caption && (
        <div style={{ marginTop: 8, fontSize: 13, color: t.fgDim, fontWeight: 500, lineHeight: 1.5, maxWidth: 720 }}>{caption}</div>
      )}
    </div>
  );
}

/* ─── PairLabel — tiny caption above a frame ─── */
function PairLabel({ t, children }) {
  return (
    <div style={{
      fontSize: 10.5, fontWeight: 800, color: t.fgMute,
      letterSpacing: 0.7, textTransform: 'uppercase',
    }}>{children}</div>
  );
}

Object.assign(window, {
  MI, PhoneShell, StatusBar, MobileTopbar, MobileBottomNav, PulseTabIcon, DotGrid,
  PulseMascotImg, Btn, BottomSheet, SkeletonRow, Banner, EmptyCard, Fab,
  SectionHeader, PairLabel, SnapsPillSm, StreakPillSm,
});
