// shield.jsx — Focus Shield + Widgets/Live Activities config sheets (V3).
//
// Fully functional on the web side: presets, persistence, activation flow, premium gating.
// OS-level enforcement/rendering is wired by the native shell later (see RELEASE_BLOCKERS.md
// and src/data/shield.js → window.EmeoShield). `Sheet`, icons and `haptic` are global.

// ── Focus Shield — two clear modes: Block Everything · Custom Blocking ──
function ShieldSheet({ onClose, accent, th, focusShield, isPremium, onLocked, onToggle, onSetMode, onSetCustom, onToast }) {
  const { t } = useI18n();
  const fs = focusShield || { enabled: false, mode: 'all', sites: [], apps: [] };
  const mode = fs.mode === 'custom' ? 'custom' : 'all';
  const sites = fs.sites || [];
  const [site, setSite] = React.useState('');
  const nativeReady = !!(window.EmeoShield && window.EmeoShield.available());
  const GOLD = typeof PREMIUM_GOLD === 'string' ? PREMIUM_GOLD : '#D4A23C';
  const toggle = (on) => { if (!isPremium) { onLocked('focus_shield'); return; } onToggle(on); };

  const addSite = () => {
    const host = String(site || '').trim().toLowerCase().replace(/^https?:\/\//, '').replace(/\/.*$/, '');
    if (!host) return;
    if (sites.includes(host)) { setSite(''); return; }
    onSetCustom({ sites: [...sites, host] });
    setSite('');
  };
  const removeSite = (h) => onSetCustom({ sites: sites.filter((s) => s !== h) });

  const Option = ({ id, icon, title, sub }) => {
    const on = mode === id;
    return (
      <button onClick={() => onSetMode(id)} style={{
        display: 'flex', alignItems: 'center', gap: 13, cursor: 'pointer', padding: '15px 16px', borderRadius: 16, textAlign: 'start',
        border: '1px solid ' + (on ? accent[0] + '88' : th.border),
        background: on ? `linear-gradient(135deg, ${accent[0]}1c, ${accent[1]}0d)` : th.surface, color: th.text,
      }}>
        <span style={{ color: on ? accent[0] : th.dim, display: 'flex' }}>{icon}</span>
        <span style={{ flex: 1, minWidth: 0 }}>
          <span style={{ fontSize: 15.5, fontWeight: 400 }}>{title}</span>
          <span style={{ display: 'block', fontSize: 12, color: th.faint, marginTop: 2 }}>{sub}</span>
        </span>
        <span style={{ width: 22, height: 22, borderRadius: '50%', flexShrink: 0, border: '2px solid ' + (on ? accent[0] : th.border2), display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          {on && <span style={{ width: 10, height: 10, borderRadius: '50%', background: accent[0] }} />}
        </span>
      </button>
    );
  };

  return (
    <Sheet title={t('focus_shield')} onClose={onClose} th={th}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
        <div style={{ fontSize: 13.5, color: th.dim, lineHeight: 1.5 }}>{t('focus_shield_desc')}</div>

        {/* Master enable (Premium) */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 13, padding: '15px 16px', borderRadius: 16,
          border: '1px solid ' + (fs.enabled ? accent[0] + '66' : th.border),
          background: fs.enabled ? `linear-gradient(135deg, ${accent[0]}18, ${accent[1]}0d)` : th.surface }}>
          <span style={{ color: accent[0], display: 'flex' }}><IconShield size={20} /></span>
          <span style={{ flex: 1, minWidth: 0 }}>
            <span style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              <span style={{ fontSize: 16, fontWeight: 400, color: th.text }}>{t('block_during_sessions')}</span>
              {!isPremium && <PremiumPill />}
            </span>
            <span style={{ display: 'block', fontSize: 12, color: th.faint, marginTop: 2 }}>{fs.enabled ? t('shield_on') : t('shield_off')}</span>
          </span>
          <MiniToggle on={!!fs.enabled && isPremium} accent={accent} th={th} onClick={() => toggle(!fs.enabled)} />
        </div>

        {/* Two modes only */}
        <div style={{ fontSize: 10.5, letterSpacing: 1.6, color: th.faint, fontWeight: 500, marginTop: 4 }}>{t('what_to_block')}</div>
        <Option id="all" icon={<IconShield size={20} />} title={t('shield_block_all')} sub={t('shield_block_all_sub')} />
        <Option id="custom" icon={<IconGear size={20} />} title={t('shield_custom')} sub={t('shield_custom_sub')} />

        {/* Custom editor — only when Custom Blocking is selected */}
        {mode === 'custom' && (
          <div className="reveal-soft" style={{ borderRadius: 16, border: '1px solid ' + th.border, background: th.surface, padding: 16 }}>
            <div style={{ fontSize: 13.5, color: th.text, marginBottom: 10 }}>{t('blocked_sites')}</div>
            <div style={{ display: 'flex', gap: 8 }}>
              <input value={site} onChange={(e) => setSite(e.target.value)} onKeyDown={(e) => { if (e.key === 'Enter') addSite(); }}
                placeholder={t('site_placeholder')} style={{ flex: 1, minWidth: 0, padding: '12px 14px', borderRadius: 12, fontSize: 14.5, fontFamily: 'inherit', background: th.surface2, border: '1px solid ' + th.border2, color: th.text, outline: 'none' }} />
              <button onClick={addSite} style={{ padding: '0 16px', borderRadius: 12, cursor: 'pointer', fontFamily: 'inherit', fontSize: 14, border: 'none', background: `linear-gradient(135deg,${accent[0]},${accent[1]})`, color: '#fff' }}>{t('add')}</button>
            </div>
            {sites.length > 0 && (
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, marginTop: 12 }}>
                {sites.map((h) => (
                  <span key={h} style={{ display: 'inline-flex', alignItems: 'center', gap: 7, padding: '7px 8px 7px 12px', borderRadius: 99, fontSize: 13, border: '1px solid ' + th.border2, background: th.surface2, color: th.text }}>
                    {h}
                    <button onClick={() => removeSite(h)} aria-label="Remove" style={{ background: th.surface, border: 'none', width: 18, height: 18, borderRadius: '50%', color: th.faint, cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><IconClose size={10} /></button>
                  </span>
                ))}
              </div>
            )}
            <div style={{ fontSize: 11.5, color: th.faint, marginTop: 12, lineHeight: 1.5 }}>{t('shield_apps_note')}</div>
          </div>
        )}

        {!nativeReady && <div style={{ fontSize: 11.5, color: th.faint, textAlign: 'center', lineHeight: 1.5 }}>{t('shield_native_note')}</div>}
      </div>
    </Sheet>
  );
}

// ── Widgets & Live Activities ─────────────────────────────
function WidgetsSheet({ onClose, accent, th, widgets, isPremium, onLocked, onUpdate }) {
  const { t } = useI18n();
  const w = widgets || { home: true, lock: false, liveActivity: false };
  const set = (key, premium) => (on) => { if (premium && !isPremium) { onLocked('widgets'); return; } onUpdate({ [key]: on }); };
  const Row = ({ icon, title, sub, on, premium, onClick }) => (
    <div style={{ display: 'flex', alignItems: 'center', gap: 13, padding: '15px 16px', borderRadius: 16, border: '1px solid ' + th.border, background: th.surface }}>
      <span style={{ color: accent[0], display: 'flex' }}>{icon}</span>
      <span style={{ flex: 1, minWidth: 0 }}>
        <span style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <span style={{ fontSize: 15.5, fontWeight: 400, color: th.text }}>{title}</span>
          {premium && !isPremium && <PremiumPill />}
        </span>
        <span style={{ display: 'block', fontSize: 12, color: th.faint, marginTop: 2 }}>{sub}</span>
      </span>
      <MiniToggle on={on} accent={accent} th={th} onClick={onClick} />
    </div>
  );
  return (
    <Sheet title={t('widgets_live')} onClose={onClose} th={th}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
        <div style={{ fontSize: 13.5, color: th.dim, lineHeight: 1.5 }}>{t('widgets_desc')}</div>
        <Row icon={<IconDevices size={20} />} title={t('home_widget')} sub={t('home_widget_sub')} on={!!w.home} premium={false} onClick={() => set('home', false)(!w.home)} />
        <Row icon={<IconLock size={20} />} title={t('lock_widget')} sub={t('lock_widget_sub')} on={!!w.lock && isPremium} premium onClick={() => set('lock', true)(!w.lock)} />
        <Row icon={<IconBolt size={20} />} title={t('live_activity')} sub={t('live_activity_sub')} on={!!w.liveActivity && isPremium} premium onClick={() => set('liveActivity', true)(!w.liveActivity)} />
        <div style={{ fontSize: 11.5, color: th.faint, textAlign: 'center', lineHeight: 1.5, marginTop: 4 }}>{t('widgets_native_note')}</div>
      </div>
    </Sheet>
  );
}

// Small reusable iOS-style toggle (matches the Settings toggles).
function MiniToggle({ on, accent, th, onClick }) {
  return (
    <button onClick={onClick} data-haptic="medium" style={{
      width: 50, height: 30, borderRadius: 99, border: 'none', cursor: 'pointer', position: 'relative', flexShrink: 0,
      background: on ? `linear-gradient(135deg,${accent[0]},${accent[1]})` : th.surface2,
      transition: 'background .2s',
    }}>
      <span style={{ position: 'absolute', top: 3, left: on ? 23 : 3, width: 24, height: 24, borderRadius: '50%', background: '#fff', transition: 'left .2s', boxShadow: '0 1px 3px rgba(0,0,0,.4)' }} />
    </button>
  );
}
