'use client';

import { useEffect, useState } from 'react';
import { applyPrefs, loadPrefs, savePrefs, DEFAULTS } from '@/lib/prefs';
import { REGIONS, ODDS_FORMATS, regionPreset } from '@/lib/oddsFormat';
import { checkoutUrl, PLAN_PRICES } from '@/lib/checkout';
import SectionHead from '@/components/vyndr/SectionHead';
import VBtn from '@/components/vyndr/VBtn';
// S6 (A1 board) — global player/team search (⌘K + window.__search).
import SearchModal from '@/components/vyndr/SearchModal';

// Augment the window with the design's global hosts (§12).
declare global {
  interface Window {
    __prefs?: () => void;
    __goPaywall?: () => void;
    __checkout?: (plan: string) => void;
    __search?: () => void;
  }
}

type Prefs = typeof DEFAULTS;

/**
 * GlobalHosts (§9/§10/§12) — mounted once in the layout. On mount it:
 *  - applies stored a11y/i18n prefs to <html> (the CSS layer keys off data-*),
 *  - registers window.__prefs / __goPaywall / __checkout,
 *  - hosts the Preferences modal and the Paywall modal.
 */
export default function GlobalHosts() {
  const [prefs, setPrefs] = useState<Prefs>(DEFAULTS);
  const [prefsOpen, setPrefsOpen] = useState(false);
  const [paywallOpen, setPaywallOpen] = useState(false);
  const [searchOpen, setSearchOpen] = useState(false);

  useEffect(() => {
    const loaded = loadPrefs();
    setPrefs(loaded);
    applyPrefs(loaded);
    window.__prefs = () => setPrefsOpen(true);
    window.__goPaywall = () => setPaywallOpen(true);
    window.__checkout = (plan: string) => {
      window.location.href = checkoutUrl(plan);
    };
    // S6 — global search: window.__search (Nav icon + mobile More sheet)
    // and the ⌘K / Ctrl-K shortcut.
    window.__search = () => setSearchOpen(true);
    const onKey = (e: KeyboardEvent) => {
      if ((e.metaKey || e.ctrlKey) && String(e.key).toLowerCase() === 'k') {
        e.preventDefault();
        setSearchOpen((o) => !o);
      }
    };
    window.addEventListener('keydown', onKey);
    return () => {
      delete window.__prefs;
      delete window.__goPaywall;
      delete window.__checkout;
      delete window.__search;
      window.removeEventListener('keydown', onKey);
    };
  }, []);

  const update = (patch: Partial<Prefs>) => {
    setPrefs((prev) => {
      let next = { ...prev, ...patch };
      // Region preset cascades odds + currency.
      if (patch.region) {
        const r = regionPreset(patch.region);
        next = { ...next, odds: r.odds, currency: r.currency };
      }
      savePrefs(next);
      applyPrefs(next);
      return next;
    });
  };

  return (
    <>
      {prefsOpen && <PrefsModal prefs={prefs} update={update} onClose={() => setPrefsOpen(false)} />}
      {paywallOpen && <PaywallModal onClose={() => setPaywallOpen(false)} />}
      <SearchModal open={searchOpen} onClose={() => setSearchOpen(false)} />
    </>
  );
}

const overlay: React.CSSProperties = {
  position: 'fixed',
  inset: 0,
  zIndex: 80,
  background: 'rgba(6,6,11,.7)',
  backdropFilter: 'blur(4px)',
  WebkitBackdropFilter: 'blur(4px)',
  display: 'flex',
  alignItems: 'center',
  justifyContent: 'center',
  padding: 16,
};

const panel: React.CSSProperties = {
  width: '100%',
  maxWidth: 460,
  maxHeight: '88vh',
  overflowY: 'auto',
  background: 'var(--bg-1)',
  border: '1px solid var(--border-hi)',
  borderRadius: 14,
  position: 'relative',
};

function Row({ label, children }: { label: string; children: React.ReactNode }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12, padding: '12px 18px', borderBottom: '1px solid var(--border)' }}>
      <span className="mono" style={{ fontSize: 12, color: 'var(--text-0)', letterSpacing: '0.04em' }}>{label}</span>
      <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', justifyContent: 'flex-end' }}>{children}</div>
    </div>
  );
}

function Seg({ active, onClick, children }: { active: boolean; onClick: () => void; children: React.ReactNode }) {
  return (
    <button
      onClick={onClick}
      aria-pressed={active}
      className="mono"
      style={{
        minHeight: 30,
        padding: '5px 10px',
        fontSize: 11,
        fontWeight: 700,
        textTransform: 'uppercase',
        letterSpacing: '0.04em',
        borderRadius: 6,
        cursor: 'pointer',
        border: `1px solid ${active ? 'var(--g-a)' : 'var(--border-hi)'}`,
        background: active ? 'color-mix(in srgb, var(--g-a) 16%, transparent)' : 'transparent',
        color: active ? 'var(--g-a)' : 'var(--text-1)',
      }}
    >
      {children}
    </button>
  );
}

function PrefsModal({ prefs, update, onClose }: { prefs: Prefs; update: (p: Partial<Prefs>) => void; onClose: () => void }) {
  return (
    <div className="fade-in" role="dialog" aria-modal="true" aria-label="Preferences" style={overlay} onClick={onClose}>
      <div className="scanlines" style={panel} onClick={(e) => e.stopPropagation()}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '14px 18px', borderBottom: '1px solid var(--border)' }}>
          <SectionHead accent="var(--g-a)">PREFERENCES</SectionHead>
          <button onClick={onClose} aria-label="Close" style={{ background: 'transparent', border: '1px solid var(--border-hi)', borderRadius: 6, color: 'var(--text-1)', width: 30, height: 30, cursor: 'pointer' }}>×</button>
        </div>

        <Row label="Region">
          {Object.keys(REGIONS).map((r) => (
            <Seg key={r} active={prefs.region === r} onClick={() => update({ region: r })}>{r}</Seg>
          ))}
        </Row>
        <Row label="Odds format">
          {ODDS_FORMATS.map((f) => (
            <Seg key={f} active={prefs.odds === f} onClick={() => update({ odds: f })}>{f.slice(0, 4)}</Seg>
          ))}
        </Row>
        <Row label="Text size">
          {(['sm', 'base', 'lg', 'xl'] as const).map((t) => (
            <Seg key={t} active={prefs.text === t} onClick={() => update({ text: t })}>{t === 'base' ? 'M' : t.toUpperCase()}</Seg>
          ))}
        </Row>
        <Row label="Reduce motion">
          <Seg active={prefs.motion === 'reduced'} onClick={() => update({ motion: prefs.motion === 'reduced' ? 'on' : 'reduced' })}>{prefs.motion === 'reduced' ? 'ON' : 'OFF'}</Seg>
        </Row>
        <Row label="High contrast">
          <Seg active={prefs.contrast === 'high'} onClick={() => update({ contrast: prefs.contrast === 'high' ? 'off' : 'high' })}>{prefs.contrast === 'high' ? 'ON' : 'OFF'}</Seg>
        </Row>
        <Row label="Colorblind-safe">
          <Seg active={prefs.cb === 'on'} onClick={() => update({ cb: prefs.cb === 'on' ? 'off' : 'on' })}>{prefs.cb === 'on' ? 'ON' : 'OFF'}</Seg>
        </Row>
        <Row label="Readable font">
          <Seg active={prefs.font === 'readable'} onClick={() => update({ font: prefs.font === 'readable' ? 'default' : 'readable' })}>{prefs.font === 'readable' ? 'ON' : 'OFF'}</Seg>
        </Row>
        <div className="mono" style={{ padding: '12px 18px', fontSize: 10.5, color: 'var(--text-2)' }}>
          Saved to this device. Totals &amp; stat lines never reformat — only odds.
        </div>
      </div>
    </div>
  );
}

function PaywallModal({ onClose }: { onClose: () => void }) {
  const tiers = [
    { id: 'analyst', name: 'Analyst', price: PLAN_PRICES.analyst, lines: ['Unlimited reads', 'Every signal', 'Kill conditions'] },
    { id: 'desk', name: 'Desk', price: PLAN_PRICES.desk, lines: ['Everything in Analyst', 'Alt-line ladder', 'Full intelligence layer'] },
  ];
  return (
    <div className="fade-in" role="dialog" aria-modal="true" aria-label="Upgrade" style={overlay} onClick={onClose}>
      <div className="scanlines" style={panel} onClick={(e) => e.stopPropagation()}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '14px 18px', borderBottom: '1px solid var(--border)' }}>
          <SectionHead accent="var(--amber)">▚ SIGNAL EXHAUSTED</SectionHead>
          <button onClick={onClose} aria-label="Close" style={{ background: 'transparent', border: '1px solid var(--border-hi)', borderRadius: 6, color: 'var(--text-1)', width: 30, height: 30, cursor: 'pointer' }}>×</button>
        </div>
        <div style={{ padding: 18 }}>
          <p className="mono" style={{ fontSize: 13, color: 'var(--text-1)', lineHeight: 1.6, marginBottom: 16 }}>
            You&apos;ve used your free reads. Unlock the full intelligence layer — founder pricing locks for life.
          </p>
          <div style={{ display: 'grid', gap: 12 }}>
            {tiers.map((t) => (
              <div key={t.id} style={{ border: '1px solid var(--border-hi)', borderRadius: 10, padding: 16 }}>
                <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 10 }}>
                  <span style={{ fontSize: 16, fontWeight: 800 }}>{t.name}</span>
                  <span className="mono" style={{ fontSize: 15, fontWeight: 800, color: 'var(--g-a)' }}>{t.price}<span style={{ fontSize: 11, color: 'var(--text-2)' }}>/mo</span></span>
                </div>
                {t.lines.map((l) => (
                  <div key={l} className="mono" style={{ fontSize: 11.5, color: 'var(--text-1)', marginBottom: 4 }}>· {l}</div>
                ))}
                <VBtn variant={t.id === 'analyst' ? 'primary' : 'outline'} style={{ width: '100%', marginTop: 12 }} onClick={() => window.__checkout && window.__checkout(t.id)}>
                  Go {t.name}
                </VBtn>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}
