// Privacy consent UI — banner + preferences modal + floating trigger
// Uses window.KDC_CONSENT for state, useI18n() for strings.

const CONSENT_I18N = {
  en: {
    bannerTitle: "Your privacy, your choice.",
    bannerBody: "We use essential cookies to run this site and, with your consent, analytics and marketing cookies to improve it. California residents: you have the right to opt out of the sale or sharing of your personal information.",
    accept: "Accept all",
    reject: "Reject non-essential",
    manage: "Manage preferences",
    policy: "Privacy policy",
    // modal
    modalTitle: "Privacy preferences",
    modalIntro: "Choose which categories of cookies and data processing you allow. You can change these any time.",
    essentialH: "Essential",
    essentialB: "Required for core site functionality — navigation, form submission, security. Always on.",
    analyticsH: "Analytics",
    analyticsB: "Aggregate, anonymized usage data that helps us improve pages, fix issues, and understand traffic.",
    marketingH: "Marketing",
    marketingB: "Advertising and retargeting cookies that may personalize ads on other sites you visit.",
    dnsH: "Do Not Sell or Share My Personal Information",
    dnsB: "California (CCPA/CPRA) right: opt out of the sale or sharing of personal information with third parties.",
    on: "On",
    off: "Off",
    save: "Save preferences",
    acceptAll: "Accept all",
    rejectAll: "Reject non-essential",
    close: "Close",
    footer: "Learn more in our",
    trigger: "Privacy choices",
    formNotice: "By submitting, you agree to our",
    formNoticeMid: "and consent to being contacted about your project.",
  },
  es: {
    bannerTitle: "Tu privacidad, tu decisión.",
    bannerBody: "Usamos cookies esenciales para operar este sitio y, con tu consentimiento, cookies de análisis y marketing para mejorarlo. Residentes de California: tienes derecho a optar por no vender o compartir tu información personal.",
    accept: "Aceptar todas",
    reject: "Rechazar no esenciales",
    manage: "Gestionar preferencias",
    policy: "Política de privacidad",
    modalTitle: "Preferencias de privacidad",
    modalIntro: "Elige qué categorías de cookies y procesamiento de datos permites. Puedes cambiarlo en cualquier momento.",
    essentialH: "Esenciales",
    essentialB: "Necesarias para el funcionamiento básico — navegación, envío de formularios, seguridad. Siempre activas.",
    analyticsH: "Analíticas",
    analyticsB: "Datos de uso agregados y anónimos que nos ayudan a mejorar páginas, corregir errores y entender el tráfico.",
    marketingH: "Marketing",
    marketingB: "Cookies de publicidad y remarketing que pueden personalizar anuncios en otros sitios que visites.",
    dnsH: "No Vender ni Compartir Mi Información Personal",
    dnsB: "Derecho bajo California (CCPA/CPRA): optar por no vender o compartir información personal con terceros.",
    on: "Activado",
    off: "Desactivado",
    save: "Guardar preferencias",
    acceptAll: "Aceptar todas",
    rejectAll: "Rechazar no esenciales",
    close: "Cerrar",
    footer: "Más información en nuestra",
    trigger: "Privacidad",
    formNotice: "Al enviar, aceptas nuestra",
    formNoticeMid: "y consientes que te contactemos sobre tu proyecto.",
  }
};
window.CONSENT_I18N = CONSENT_I18N;

function ConsentUI() {
  const { lang } = useI18n();
  const s = CONSENT_I18N[lang];
  const [state, setState] = React.useState(() => window.KDC_CONSENT.get());
  const [showBanner, setShowBanner] = React.useState(false);
  const [showModal, setShowModal] = React.useState(false);

  React.useEffect(() => {
    const current = window.KDC_CONSENT.get();
    setState(current);
    if (!current.decided) {
      const t = setTimeout(() => setShowBanner(true), 400);
      return () => clearTimeout(t);
    }
  }, []);

  React.useEffect(() => {
    const onOpen = () => { setShowModal(true); setShowBanner(false); };
    const onChange = () => setState(window.KDC_CONSENT.get());
    window.addEventListener('kdc-consent-open', onOpen);
    window.addEventListener('kdc-consent-change', onChange);
    return () => {
      window.removeEventListener('kdc-consent-open', onOpen);
      window.removeEventListener('kdc-consent-change', onChange);
    };
  }, []);

  const acceptAll = () => {
    window.KDC_CONSENT.set({ analytics: true, marketing: true, doNotSell: false });
    setShowBanner(false); setShowModal(false);
  };
  const rejectAll = () => {
    window.KDC_CONSENT.set({ analytics: false, marketing: false, doNotSell: true });
    setShowBanner(false); setShowModal(false);
  };
  const savePrefs = () => {
    window.KDC_CONSENT.set(state);
    setShowBanner(false); setShowModal(false);
  };

  return (
    <>
      {/* Banner */}
      {showBanner && !showModal && (
        <div role="dialog" aria-label={s.bannerTitle} className="consent-banner">
          <div className="consent-banner-inner">
            <div className="consent-banner-text">
              <div className="consent-banner-title">{s.bannerTitle}</div>
              <p>{s.bannerBody} <a href="privacy.html">{s.policy} →</a></p>
            </div>
            <div className="consent-banner-actions">
              <button className="consent-btn consent-btn-ghost" onClick={() => setShowModal(true)}>{s.manage}</button>
              <button className="consent-btn consent-btn-ghost" onClick={rejectAll}>{s.reject}</button>
              <button className="consent-btn consent-btn-primary" onClick={acceptAll}>{s.accept}</button>
            </div>
          </div>
        </div>
      )}

      {/* Modal */}
      {showModal && (
        <div className="consent-modal-backdrop" onClick={(e) => { if (e.target === e.currentTarget) setShowModal(false); }}>
          <div role="dialog" aria-modal="true" aria-label={s.modalTitle} className="consent-modal">
            <div className="consent-modal-head">
              <div>
                <div className="eyebrow">— CCPA / CPRA</div>
                <h3>{s.modalTitle}</h3>
              </div>
              <button onClick={() => setShowModal(false)} className="consent-close" aria-label={s.close}>×</button>
            </div>
            <p className="consent-modal-intro">{s.modalIntro}</p>

            <div className="consent-row">
              <div className="consent-row-text">
                <div className="consent-row-title">{s.essentialH}</div>
                <div className="consent-row-body">{s.essentialB}</div>
              </div>
              <Toggle checked={true} disabled labelOn={s.on} labelOff={s.off}/>
            </div>
            <div className="consent-row">
              <div className="consent-row-text">
                <div className="consent-row-title">{s.analyticsH}</div>
                <div className="consent-row-body">{s.analyticsB}</div>
              </div>
              <Toggle checked={state.analytics} onChange={v => setState(st => ({...st, analytics: v}))} labelOn={s.on} labelOff={s.off}/>
            </div>
            <div className="consent-row">
              <div className="consent-row-text">
                <div className="consent-row-title">{s.marketingH}</div>
                <div className="consent-row-body">{s.marketingB}</div>
              </div>
              <Toggle checked={state.marketing} onChange={v => setState(st => ({...st, marketing: v}))} labelOn={s.on} labelOff={s.off}/>
            </div>
            <div className="consent-row" style={{ background: 'var(--bg-alt)', margin: '16px -20px 0', padding: '20px' }}>
              <div className="consent-row-text">
                <div className="consent-row-title">{s.dnsH}</div>
                <div className="consent-row-body">{s.dnsB}</div>
              </div>
              <Toggle checked={state.doNotSell} onChange={v => setState(st => ({...st, doNotSell: v}))} labelOn={s.on} labelOff={s.off}/>
            </div>

            <div className="consent-modal-actions">
              <a href="privacy.html" className="consent-policy-link">{s.footer} {s.policy} →</a>
              <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
                <button className="consent-btn consent-btn-ghost" onClick={rejectAll}>{s.rejectAll}</button>
                <button className="consent-btn consent-btn-ghost" onClick={acceptAll}>{s.acceptAll}</button>
                <button className="consent-btn consent-btn-primary" onClick={savePrefs}>{s.save}</button>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Floating re-open trigger */}
      {!showBanner && !showModal && state.decided && (
        <button className="consent-trigger" onClick={() => setShowModal(true)} aria-label={s.trigger}>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8">
            <path d="M12 2v4M12 18v4M4.93 4.93l2.83 2.83M16.24 16.24l2.83 2.83M2 12h4M18 12h4M4.93 19.07l2.83-2.83M16.24 7.76l2.83-2.83"/>
          </svg>
          <span>{s.trigger}</span>
        </button>
      )}
    </>
  );
}

function Toggle({ checked, onChange, disabled, labelOn, labelOff }) {
  return (
    <button
      role="switch"
      aria-checked={checked}
      disabled={disabled}
      onClick={() => !disabled && onChange(!checked)}
      className={`consent-toggle ${checked ? 'on' : ''} ${disabled ? 'disabled' : ''}`}
    >
      <span className="consent-toggle-dot"/>
      <span className="consent-toggle-label">{checked ? labelOn : labelOff}</span>
    </button>
  );
}

// Form consent checkbox — reusable
function FormPrivacyNotice({ checked, onChange, dark }) {
  const { lang } = useI18n();
  const s = CONSENT_I18N[lang];
  return (
    <label className="form-privacy-notice" style={dark ? { color: 'rgba(250,248,244,0.8)' } : undefined}>
      <input type="checkbox" checked={checked} onChange={e => onChange(e.target.checked)} required/>
      <span>
        {s.formNotice} <a href="privacy.html" style={dark ? { color: '#fff' } : undefined}>{s.policy.toLowerCase()}</a> {s.formNoticeMid}
      </span>
    </label>
  );
}

window.ConsentUI = ConsentUI;
window.FormPrivacyNotice = FormPrivacyNotice;
