// Shared UI primitives — theme, BottomNav, headers, speaker button

window.THEMES = {
  'red-gold':   { accent: '#B91C1C', accentDark: '#8B1010', accentSoft: '#FEF2F2', gold: '#C9A961', name: 'แดงมงคล' },
  'blue-gold':  { accent: '#1E3A8A', accentDark: '#172554', accentSoft: '#EFF6FF', gold: '#C9A961', name: 'น้ำเงินสุขุม' },
  'green-gold': { accent: '#166534', accentDark: '#14532D', accentSoft: '#F0FDF4', gold: '#C9A961', name: 'เขียวมงคล' },
};

window.useTheme = () => {
  const { tweaks } = useApp();
  return THEMES[tweaks.theme] || THEMES['red-gold'];
};

window.useFontScale = () => {
  const { tweaks } = useApp();
  return tweaks.bigFont ? 1.15 : 1.0;
};

// Speaker button — pill with 🔊 icon, fake TTS (visual only)
window.SpeakerBtn = function SpeakerBtn({ label = 'ฟังสรุป', onSpeak }) {
  const theme = useTheme();
  const [speaking, setSpeaking] = useState(false);
  const handle = () => {
    setSpeaking(true);
    if (onSpeak) onSpeak();
    // try browser TTS if available
    if (window.speechSynthesis && onSpeak) {
      try {
        const text = typeof onSpeak === 'function' ? onSpeak() : '';
        if (typeof text === 'string' && text) {
          const u = new SpeechSynthesisUtterance(text);
          u.lang = 'th-TH';
          u.rate = 0.95;
          window.speechSynthesis.cancel();
          window.speechSynthesis.speak(u);
        }
      } catch (e) {}
    }
    setTimeout(() => setSpeaking(false), 2200);
  };
  return (
    <button onClick={handle} className="speaker-btn" style={{
      display: 'inline-flex', alignItems: 'center', gap: 6,
      padding: '7px 12px', borderRadius: 999,
      border: `1.5px solid ${theme.accent}22`,
      background: speaking ? theme.accent : '#fff',
      color: speaking ? '#fff' : theme.accent,
      fontSize: 13, fontWeight: 600, cursor: 'pointer',
      transition: 'all .2s',
    }}>
      <span style={{ fontSize: 14 }}>{speaking ? '🔈' : '🔊'}</span>
      <span>{label}</span>
    </button>
  );
};

// Bottom navigation bar
window.BottomNav = function BottomNav() {
  const { route, go } = useApp();
  const theme = useTheme();
  const MAIN_ROUTES = ['home', 'lottery', 'dream', 'lucky'];
  const maxWidth = MAIN_ROUTES.includes(route.name) ? 960 : 500;
  const items = [
    { id: 'home',    label: 'หน้าแรก',   icon: IconHome },
    { id: 'dream',   label: 'ทำนายฝัน',  icon: IconMoon },
    { id: 'lucky',   label: 'เลขมงคล',   icon: IconStar },
    { id: 'profile', label: 'โปรไฟล์',   icon: IconUser },
  ];
  const activeId = route.name === 'lottery' ? 'home' : route.name;
  return (
    <div className="bottom-nav-responsive" style={{
      position: 'fixed', left: 0, right: 0, bottom: 0, zIndex: 40,
      maxWidth, margin: '0 auto',
      background: '#fff', borderTop: '1px solid #EDE7DC',
      padding: '8px 8px',
      paddingBottom: 'calc(8px + env(safe-area-inset-bottom))',
      display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 4,
      fontFamily: 'inherit',
    }}>
      {items.map(it => {
        const active = activeId === it.id;
        const Icon = it.icon;
        return (
          <button key={it.id} onClick={() => go(it.id)} style={{
            background: 'transparent', border: 0, padding: '6px 4px',
            display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 3,
            color: active ? theme.accent : '#8C8678',
            cursor: 'pointer',
          }}>
            <Icon size={22} active={active} color={active ? theme.accent : '#8C8678'} />
            <div style={{ fontSize: 11, fontWeight: active ? 700 : 500 }}>{it.label}</div>
          </button>
        );
      })}
    </div>
  );
};

// Phone shell — responsive container (no phone frame in production)
window.PhoneShell = function PhoneShell({ children, showBottomNav = true, bg = '#FAF7F2', noPadding = false }) {
  const { route } = useApp();
  const MAIN_ROUTES = ['home', 'lottery', 'dream', 'lucky'];
  const maxWidth = MAIN_ROUTES.includes(route.name) ? 960 : 500;
  return (
    <div style={{
      width: '100%', maxWidth,
      minHeight: '100vh',
      background: bg,
      position: 'relative',
      margin: '0 auto',
      fontFamily: "'Noto Sans Thai', 'IBM Plex Sans Thai', sans-serif",
    }}>
      {showBottomNav && <TopHeader />}
      <div className="main-content-wrap" style={{
        paddingTop: 'env(safe-area-inset-top)',
        paddingBottom: showBottomNav ? 'calc(68px + env(safe-area-inset-bottom))' : 'env(safe-area-inset-bottom)',
        minHeight: '100vh',
        overflowX: 'hidden',
      }}>
        {children}
      </div>
      {showBottomNav && <BottomNav />}
    </div>
  );
};

// Simple icons (stroke-based, cultural neutral)
window.IconHome = ({ size = 22, color = '#000', active }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill={active ? color : 'none'} stroke={color} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
    <path d="M3 11l9-7 9 7v10a1 1 0 01-1 1h-5v-6h-6v6H4a1 1 0 01-1-1V11z"/>
  </svg>
);
window.IconMoon = ({ size = 22, color = '#000', active }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill={active ? color : 'none'} stroke={color} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
    <path d="M21 13A9 9 0 0111 3a7 7 0 1010 10z"/>
  </svg>
);
window.IconStar = ({ size = 22, color = '#000', active }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill={active ? color : 'none'} stroke={color} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
    <path d="M12 3l2.7 5.8 6.3.8-4.6 4.3 1.2 6.3L12 17.3 6.4 20.2l1.2-6.3L3 9.6l6.3-.8L12 3z"/>
  </svg>
);
window.IconUser = ({ size = 22, color = '#000', active }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
    <circle cx="12" cy="8" r="4" fill={active ? color : 'none'}/>
    <path d="M4 21a8 8 0 0116 0" fill={active ? color : 'none'}/>
  </svg>
);
window.IconBack = ({ size = 22, color = '#000' }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
    <path d="M15 18l-6-6 6-6"/>
  </svg>
);
window.IconMic = ({ size = 22, color = '#fff' }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
    <rect x="9" y="2" width="6" height="12" rx="3" fill={color}/>
    <path d="M5 11a7 7 0 0014 0M12 18v4"/>
  </svg>
);
window.IconCamera = ({ size = 20, color = '#B91C1C' }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
    <path d="M4 8h3l2-3h6l2 3h3a1 1 0 011 1v10a1 1 0 01-1 1H4a1 1 0 01-1-1V9a1 1 0 011-1z"/>
    <circle cx="12" cy="13" r="4"/>
  </svg>
);
window.IconClock = ({ size = 14, color = '#8C8678' }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
    <circle cx="12" cy="12" r="9"/>
    <path d="M12 7v5l3 2"/>
  </svg>
);
window.IconTrophy = ({ size = 18, color = '#C9A961' }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill={color} stroke={color} strokeWidth="1" strokeLinejoin="round">
    <path d="M7 3h10v4a5 5 0 01-10 0V3zM5 4H3v2a4 4 0 004 4M19 4h2v2a4 4 0 01-4 4M9 12h6l-1 4h-4l-1-4zM7 20h10v2H7z"/>
  </svg>
);
window.IconArrowUp = ({ size = 12, color = '#16A34A' }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="3" strokeLinecap="round" strokeLinejoin="round">
    <path d="M7 14l5-5 5 5"/>
  </svg>
);

// Desktop top header — hidden on mobile via CSS, shown on ≥768px
window.TopHeader = function TopHeader() {
  const { route, go, user } = useApp();
  const theme = useTheme();
  const items = [
    { id: 'home',    label: 'หน้าแรก' },
    { id: 'dream',   label: 'ทำนายฝัน' },
    { id: 'lucky',   label: 'เลขมงคล' },
    { id: 'profile', label: 'โปรไฟล์' },
  ];
  const activeId = route.name === 'lottery' ? 'home' : route.name;
  return (
    <div className="desktop-top-header" style={{
      position: 'fixed', top: 0, left: 0, right: 0, zIndex: 50,
      background: '#fff', borderBottom: '1px solid #EDE7DC',
      boxShadow: '0 1px 8px rgba(90,85,70,0.08)',
    }}>
      <div style={{
        maxWidth: 960, margin: '0 auto', height: 60,
        display: 'flex', alignItems: 'center', padding: '0 24px', gap: 0,
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, minWidth: 160 }}>
          <div style={{
            width: 34, height: 34, borderRadius: 9,
            background: `linear-gradient(135deg, ${theme.accent}, ${theme.accentDark})`,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            color: '#fff', fontWeight: 800, fontSize: 18,
          }}>฿</div>
          <div style={{ fontSize: 16, fontWeight: 800, color: '#1A1A1A' }}>สุ่มเลข</div>
        </div>
        <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 4 }}>
          {items.map(item => {
            const active = activeId === item.id;
            return (
              <button key={item.id} onClick={() => go(item.id)} style={{
                padding: '7px 16px', borderRadius: 8,
                border: active ? `1.5px solid ${theme.accent}33` : '1.5px solid transparent',
                background: active ? `${theme.accent}0F` : 'transparent',
                color: active ? theme.accent : '#5A5546',
                fontSize: 14, fontWeight: active ? 700 : 500,
                cursor: 'pointer', fontFamily: 'inherit', transition: 'all .15s',
              }}>{item.label}</button>
            );
          })}
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, minWidth: 160, justifyContent: 'flex-end' }}>
          <div style={{ textAlign: 'right' }}>
            <div style={{ fontSize: 11, color: '#8C8678' }}>ยินดีต้อนรับ</div>
            <div style={{ fontSize: 13, fontWeight: 700, color: '#1A1A1A' }}>{user?.name || 'ผู้ใช้'}</div>
          </div>
          <button onClick={() => go('profile')} style={{
            width: 36, height: 36, borderRadius: 999, border: 0,
            background: `${theme.accent}15`, color: theme.accent,
            fontWeight: 800, fontSize: 14, cursor: 'pointer', fontFamily: 'inherit',
          }}>{user?.name?.[0] || '?'}</button>
        </div>
      </div>
    </div>
  );
};
