// Shared Huul UI primitives — device frame, buttons, avatar, sheet, toast.

const { useState, useEffect, useRef, useCallback } = React;

// Thin wrapper around IOSDevice that exposes a scrollable content area
// and hides the iOS nav bar (we roll our own, closer to the reference).
function HuulDevice({ children, width = 402, height = 844, bg = '#F2F2F4' }) {
  return (
    <div style={{
      width, height, borderRadius: 48, overflow: 'hidden',
      position: 'relative', background: bg,
      boxShadow: '0 40px 80px rgba(0,0,0,0.18), 0 0 0 1px rgba(0,0,0,0.12), 0 2px 6px rgba(0,0,0,0.08)',
      fontFamily: HUUL_TOKENS.font.stack,
      WebkitFontSmoothing: 'antialiased',
      color: HUUL_TOKENS.color.ink,
    }}>
      {/* dynamic island */}
      <div style={{
        position: 'absolute', top: 11, left: '50%', transform: 'translateX(-50%)',
        width: 126, height: 37, borderRadius: 24, background: '#000', zIndex: 50,
      }} />
      {/* status bar */}
      <div style={{ position: 'absolute', top: 0, left: 0, right: 0, zIndex: 10 }}>
        <IOSStatusBar />
      </div>
      {/* content */}
      <div style={{ height: '100%', overflow: 'hidden', position: 'relative' }}>
        {children}
      </div>
      {/* home indicator */}
      <div style={{
        position: 'absolute', bottom: 0, left: 0, right: 0, zIndex: 60,
        height: 34, display: 'flex', justifyContent: 'center', alignItems: 'flex-end',
        paddingBottom: 8, pointerEvents: 'none',
      }}>
        <div style={{ width: 139, height: 5, borderRadius: 100, background: 'rgba(0,0,0,0.25)' }} />
      </div>
    </div>
  );
}

// ─── Avatar ───────────────────────────────────────────────────────
function Avatar({ profile, size = 88 }) {
  const fontSize = Math.round(size * 0.4);
  return (
    <div style={{
      width: size, height: size, borderRadius: size / 2,
      background: profile.avatarBg || 'linear-gradient(135deg,#8EB8E8 0%,#5A7FBF 100%)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      color: '#fff', fontSize, fontWeight: 600, letterSpacing: -0.5,
      boxShadow: '0 2px 8px rgba(0,0,0,0.08), inset 0 0 0 3px rgba(255,255,255,0.9)',
      flexShrink: 0,
    }}>
      {profile.avatarInitial || profile.businessName?.[0] || '?'}
    </div>
  );
}

// ─── Buttons ──────────────────────────────────────────────────────
function PrimaryButton({ children, onClick, icon, disabled, style = {}, variant = 'blue' }) {
  const [pressed, setPressed] = useState(false);
  const bg = variant === 'wa'
    ? (pressed ? HUUL_TOKENS.color.waPressed : HUUL_TOKENS.color.wa)
    : (pressed ? HUUL_TOKENS.color.accentPressed : HUUL_TOKENS.color.accent);
  const sh = variant === 'wa' ? HUUL_TOKENS.shadow.wa : HUUL_TOKENS.shadow.btn;
  return (
    <button
      onPointerDown={() => setPressed(true)}
      onPointerUp={() => setPressed(false)}
      onPointerLeave={() => setPressed(false)}
      onClick={disabled ? undefined : onClick}
      disabled={disabled}
      style={{
        width: '100%', height: 54, borderRadius: 14, border: 'none',
        background: disabled ? '#D1D1D6' : bg,
        color: '#fff', fontSize: 17, fontWeight: 600,
        fontFamily: HUUL_TOKENS.font.stack,
        display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
        boxShadow: disabled ? 'none' : sh,
        transform: pressed && !disabled ? 'scale(0.98)' : 'scale(1)',
        transition: 'transform 140ms cubic-bezier(.4,0,.2,1), background 140ms',
        cursor: disabled ? 'not-allowed' : 'pointer',
        letterSpacing: -0.2,
        ...style,
      }}>
      {icon}
      <span>{children}</span>
    </button>
  );
}

function GhostButton({ children, onClick, icon, style = {} }) {
  const [pressed, setPressed] = useState(false);
  return (
    <button
      onPointerDown={() => setPressed(true)}
      onPointerUp={() => setPressed(false)}
      onPointerLeave={() => setPressed(false)}
      onClick={onClick}
      style={{
        height: 44, padding: '0 16px', borderRadius: 12, border: 'none',
        background: pressed ? 'rgba(0,0,0,0.08)' : 'rgba(0,0,0,0.04)',
        color: HUUL_TOKENS.color.ink, fontSize: 15, fontWeight: 500,
        fontFamily: HUUL_TOKENS.font.stack,
        display: 'inline-flex', alignItems: 'center', gap: 6,
        cursor: 'pointer', transition: 'background 120ms',
        ...style,
      }}>
      {icon}
      {children}
    </button>
  );
}

function IconButton({ icon, onClick, style = {}, size = 36, bg = 'rgba(0,0,0,0.05)' }) {
  const [pressed, setPressed] = useState(false);
  return (
    <button
      onPointerDown={() => setPressed(true)}
      onPointerUp={() => setPressed(false)}
      onPointerLeave={() => setPressed(false)}
      onClick={onClick}
      style={{
        width: size, height: size, borderRadius: size / 2, border: 'none',
        background: pressed ? 'rgba(0,0,0,0.12)' : bg,
        color: HUUL_TOKENS.color.ink,
        display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
        cursor: 'pointer', transition: 'background 120ms, transform 120ms',
        transform: pressed ? 'scale(0.94)' : 'scale(1)',
        ...style,
      }}>
      {icon}
    </button>
  );
}

// ─── Inputs ───────────────────────────────────────────────────────
function TextField({ value, onChange, placeholder, prefix, suffix, multiline, rows = 3, autoFocus, style = {}, inputStyle = {} }) {
  const [focused, setFocused] = useState(false);
  const Tag = multiline ? 'textarea' : 'input';
  return (
    <div style={{
      display: 'flex', alignItems: multiline ? 'flex-start' : 'center',
      background: '#fff', borderRadius: 14,
      padding: multiline ? '12px 14px' : '0 14px',
      minHeight: multiline ? undefined : 52,
      border: `1.5px solid ${focused ? HUUL_TOKENS.color.accent : 'transparent'}`,
      boxShadow: focused ? '0 0 0 4px rgba(10,132,255,0.15)' : HUUL_TOKENS.shadow.card,
      transition: 'border-color 140ms, box-shadow 140ms',
      ...style,
    }}>
      {prefix && <span style={{ color: HUUL_TOKENS.color.ink3, marginRight: 4, fontSize: 17 }}>{prefix}</span>}
      <Tag
        value={value}
        onChange={(e) => onChange(e.target.value)}
        placeholder={placeholder}
        autoFocus={autoFocus}
        rows={multiline ? rows : undefined}
        onFocus={() => setFocused(true)}
        onBlur={() => setFocused(false)}
        style={{
          flex: 1, border: 'none', outline: 'none', background: 'transparent',
          fontSize: 17, fontFamily: HUUL_TOKENS.font.stack,
          color: HUUL_TOKENS.color.ink, padding: 0,
          resize: 'none', lineHeight: 1.4,
          ...inputStyle,
        }} />
      {suffix && <span style={{ marginLeft: 8 }}>{suffix}</span>}
    </div>
  );
}

// ─── Bottom sheet ─────────────────────────────────────────────────
function BottomSheet({ open, onClose, children, title }) {
  return (
    <>
      <div
        onClick={onClose}
        style={{
          position: 'absolute', inset: 0,
          background: open ? 'rgba(0,0,0,0.35)' : 'transparent',
          pointerEvents: open ? 'auto' : 'none',
          transition: 'background 240ms',
          zIndex: 100,
        }} />
      <div style={{
        position: 'absolute', left: 0, right: 0, bottom: 0,
        background: '#F2F2F4', borderTopLeftRadius: 24, borderTopRightRadius: 24,
        transform: open ? 'translateY(0)' : 'translateY(100%)',
        transition: 'transform 320ms cubic-bezier(.4,0,.2,1)',
        zIndex: 101, boxShadow: '0 -8px 30px rgba(0,0,0,0.12)',
        maxHeight: '88%', display: 'flex', flexDirection: 'column',
      }}>
        <div style={{ display: 'flex', justifyContent: 'center', padding: '10px 0 4px' }}>
          <div style={{ width: 36, height: 5, borderRadius: 3, background: 'rgba(0,0,0,0.18)' }} />
        </div>
        {title && (
          <div style={{
            textAlign: 'center', padding: '8px 20px 4px',
            fontSize: 17, fontWeight: 600,
          }}>{title}</div>
        )}
        <div style={{ overflow: 'auto', padding: '12px 16px 28px' }}>
          {children}
        </div>
      </div>
    </>
  );
}

// ─── Toast ────────────────────────────────────────────────────────
function Toast({ message, visible }) {
  return (
    <div style={{
      position: 'absolute', top: 70, left: '50%',
      transform: `translate(-50%, ${visible ? '0' : '-20px'})`,
      opacity: visible ? 1 : 0,
      transition: 'all 220ms cubic-bezier(.4,0,.2,1)',
      background: 'rgba(30,30,32,0.95)', color: '#fff',
      padding: '10px 18px', borderRadius: 999, fontSize: 14, fontWeight: 500,
      backdropFilter: 'blur(10px)', zIndex: 200,
      boxShadow: '0 8px 20px rgba(0,0,0,0.2)',
      pointerEvents: 'none',
    }}>
      {message}
    </div>
  );
}

// Hook: auto-hiding toast
function useToast() {
  const [toast, setToast] = useState({ message: '', visible: false });
  const show = useCallback((message) => {
    setToast({ message, visible: true });
    setTimeout(() => setToast((t) => ({ ...t, visible: false })), 1800);
  }, []);
  return [toast, show];
}

// ─── Tab bar ─────────────────────────────────────────────────────
function TabBar({ active, onTab, tabStyle = 'C' }) {
  const allTabs = {
    profile:   { id: 'profile',   label: 'Preview',   icon: <IconEye size={20}/> },
    bio:       { id: 'bio',       label: 'My Page',   icon: <IconLink size={20}/> },
    dashboard: { id: 'dashboard', label: 'Products',  icon: <IconStore size={20}/> },
    analytics: { id: 'analytics', label: 'Analytics', icon: <IconChart size={20}/> },
    settings:  { id: 'settings',  label: 'Settings',  icon: <IconSettings size={20}/> },
  };
  const orders = {
    B: ['profile', 'bio', 'dashboard', 'analytics', 'settings'],
    C: ['dashboard', 'profile', 'analytics', 'settings'],
  };
  const tabs = (orders[tabStyle] || orders.C).map(id => allTabs[id]);
  return (
    <div style={{
      position: 'absolute', bottom: 0, left: 0, right: 0, zIndex: 80,
      background: 'rgba(250,250,252,0.92)',
      backdropFilter: 'blur(20px)',
      WebkitBackdropFilter: 'blur(20px)',
      borderTop: '1px solid rgba(60,60,67,0.1)',
      display: 'flex', paddingBottom: 20, paddingTop: 8,
    }}>
      {tabs.map(t => {
        const isActive = active === t.id;
        return (
          <button key={t.id} onClick={() => onTab(t.id)} style={{
            flex: 1, border: 'none', background: 'transparent',
            display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 3,
            cursor: 'pointer', padding: '4px 0',
            color: isActive ? HUUL_TOKENS.color.accent : HUUL_TOKENS.color.ink3,
            fontFamily: HUUL_TOKENS.font.stack,
            transition: 'color 150ms',
          }}>
            {t.icon}
            <span style={{ fontSize: 10, fontWeight: isActive ? 600 : 400, letterSpacing: 0.1 }}>
              {t.label}
            </span>
          </button>
        );
      })}
    </div>
  );
}

Object.assign(window, {
  HuulDevice, Avatar, PrimaryButton, GhostButton, IconButton,
  TextField, BottomSheet, Toast, useToast, TabBar,
});
