// Eu Faço Parte — App shell + Tweaks panel

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accentHue": 250,
  "accentChroma": 0.11,
  "accentLightness": 0.40,
  "paperWarmth": 75,
  "paperLightness": 0.975,
  "serif": "Crimson Pro",
  "sans": "Inter Tight",
  "mono": "JetBrains Mono",
  "displayScale": 1.0
}/*EDITMODE-END*/;

const SERIF_OPTIONS  = ['Crimson Pro', 'Source Serif 4', 'EB Garamond', 'Cormorant Garamond', 'Libre Caslon Text', 'Playfair Display'];
const SANS_OPTIONS   = ['Inter Tight', 'Geist', 'DM Sans', 'Manrope', 'Work Sans', 'Plus Jakarta Sans'];
const MONO_OPTIONS   = ['JetBrains Mono', 'IBM Plex Mono', 'Space Mono', 'Geist Mono', 'Fira Code'];

const ACCENT_PRESETS = [
  { name: 'Azul Inst.',   h: 250, c: 0.11, l: 0.40 },
  { name: 'Terracotta',   h: 38, c: 0.135, l: 0.55 },
  { name: 'Burnt Sienna', h: 50, c: 0.135, l: 0.50 },
  { name: 'Forest',       h: 145, c: 0.07, l: 0.40 },
  { name: 'Indigo',       h: 270, c: 0.10, l: 0.40 },
  { name: 'Charcoal',     h: 60, c: 0.015, l: 0.25 },
];

function applyTweaks(tw) {
  const r = document.documentElement.style;
  r.setProperty('--accent',
    `oklch(${tw.accentLightness} ${tw.accentChroma} ${tw.accentHue})`);
  r.setProperty('--bordeaux',
    `oklch(${tw.accentLightness} ${tw.accentChroma} ${tw.accentHue})`);
  r.setProperty('--bordeaux-2',
    `oklch(${Math.max(0.18, tw.accentLightness - 0.08)} ${tw.accentChroma * 0.9} ${tw.accentHue})`);
  r.setProperty('--terracotta',
    `oklch(${Math.min(0.7, tw.accentLightness + 0.18)} ${tw.accentChroma * 1.15} ${tw.accentHue + 10})`);
  r.setProperty('--verdegrowth', 'rgb(105, 216, 128)');

  r.setProperty('--paper',   `oklch(${tw.paperLightness} 0.008 ${tw.paperWarmth})`);
  r.setProperty('--paper-2', `oklch(${tw.paperLightness - 0.03} 0.015 ${tw.paperWarmth - 5})`);
  r.setProperty('--paper-3', `oklch(${tw.paperLightness - 0.07} 0.02 ${tw.paperWarmth - 10})`);

  r.setProperty('--serif', `'${tw.serif}', Georgia, serif`);
  r.setProperty('--sans',  `'${tw.sans}', -apple-system, sans-serif`);
  r.setProperty('--mono',  `'${tw.mono}', ui-monospace, monospace`);

  ensureFont(tw.serif);
  ensureFont(tw.sans);
  ensureFont(tw.mono);
}

const _loadedFonts = new Set();
function ensureFont(family) {
  if (!family || _loadedFonts.has(family)) return;
  _loadedFonts.add(family);
  const name = family.replace(/ /g, '+');
  const link = document.createElement('link');
  link.rel = 'stylesheet';
  link.href = `https://fonts.googleapis.com/css2?family=${name}:ital,wght@0,400;0,500;0,600;0,700;1,400;1,500&display=swap`;
  document.head.appendChild(link);
}

// --- Donorbox Widget ---
const DonorboxWidget = () => {
  const ref = React.useRef(null);
  React.useEffect(() => {
    if (!ref.current) return;
    ref.current.innerHTML =
      '<dbox-widget campaign="doacoes-23" type="donation_form" interval="1 M" enable-auto-scroll="true"></dbox-widget>';
    if (!document.querySelector('script[data-dbox]')) {
      const s = document.createElement('script');
      s.type = 'module';
      s.src = 'https://donorbox.org/widgets.js';
      s.async = true;
      s.setAttribute('data-dbox', '');
      document.head.appendChild(s);
    }
  }, []);
  return <div ref={ref} className="dbox-wrap"></div>;
};

// --- Modal de Doação ---
const DonationModal = ({ onClose }) => {
  const [stack, setStack] = React.useState(['region']);
  const step = stack[stack.length - 1];
  const go   = (s) => setStack(prev => [...prev, s]);
  const back = ()  => setStack(prev => prev.slice(0, -1));

  const [copied, setCopied] = React.useState(false);
  const copyPix = () => {
    navigator.clipboard?.writeText('58009272/001-32');
    setCopied(true);
    setTimeout(() => setCopied(false), 2000);
  };

  React.useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    document.addEventListener('keydown', onKey);
    document.body.style.overflow = 'hidden';
    return () => {
      document.removeEventListener('keydown', onKey);
      document.body.style.overflow = '';
    };
  }, [onClose]);

  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className={`modal-box${step === 'form' ? ' modal-box--wide' : ''}`} onClick={e => e.stopPropagation()}>
        <button className="modal-close" onClick={onClose} aria-label="×">✕</button>

        {stack.length > 1 && (
          <button className="modal-back" onClick={back}>{t('donation.back')}</button>
        )}

        {step === 'region' && (
          <div className="modal-step">
            <span className="eyebrow"><span className="dot"></span> {t('donation.eyebrow')}</span>
            <h2 className="modal-title">{t('donation.region_q')}</h2>
            <p className="modal-sub">{t('donation.region_sub')}</p>
            <div className="modal-regions">
              <button className="modal-region-btn" onClick={() => go('form')}>
                <span className="region-flag">🇪🇺</span>
                <span className="region-name">{t('donation.r_europe')}</span>
              </button>
              <button className="modal-region-btn" onClick={() => go('form')}>
                <span className="region-flag">🇨🇭</span>
                <span className="region-name">{t('donation.r_swiss')}</span>
              </button>
              <button className="modal-region-btn" onClick={() => go('br-method')}>
                <span className="region-flag">🇧🇷</span>
                <span className="region-name">{t('donation.r_brazil')}</span>
              </button>
            </div>
          </div>
        )}

        {step === 'br-method' && (
          <div className="modal-step">
            <span className="eyebrow"><span className="dot"></span> {t('donation.br_eyebrow')}</span>
            <h2 className="modal-title">{t('donation.br_q')}</h2>
            <div className="modal-methods">
              <button className="modal-method-btn" onClick={() => go('pix')}>
                <span className="method-name">{t('donation.m_pix')}</span>
                <span className="method-desc">{t('donation.m_pix_d')}</span>
              </button>
              <button className="modal-method-btn" onClick={() => go('form')}>
                <span className="method-name">{t('donation.m_card')}</span>
                <span className="method-desc">{t('donation.m_card_d')}</span>
              </button>
            </div>
          </div>
        )}

        {step === 'pix' && (
          <div className="modal-step">
            <span className="eyebrow"><span className="dot"></span> {t('donation.pix_eyebrow')}</span>
            <h2 className="modal-title">{t('donation.pix_title')}</h2>
            <p className="modal-sub">{t('donation.pix_sub')}</p>
            <div className="modal-pix-box">
              <span className="pix-label">{t('donation.pix_label')}</span>
              <span className="pix-key">58009272/001-32</span>
              <button className="pix-copy" onClick={copyPix}>{copied ? t('donation.pix_copied') : t('donation.pix_copy')}</button>
            </div>
            <p className="modal-pix-note" dangerouslySetInnerHTML={tHTML('donation.pix_note')} />
          </div>
        )}

        {step === 'form' && (
          <div className="modal-step modal-step--form">
            <DonorboxWidget key={stack.join('-')} />
          </div>
        )}
      </div>
    </div>
  );
};

const LiquidGlassFilter = () => (
  <svg aria-hidden="true" style={{ position: 'fixed', width: 0, height: 0, overflow: 'hidden', pointerEvents: 'none' }}>
    <defs>
      <filter id="glass-bd" colorInterpolationFilters="sRGB">
        <feGaussianBlur stdDeviation="24" result="blur" />
        <feColorMatrix type="saturate" values="2.2" in="blur" result="sat" />
        <feComponentTransfer in="sat" result="bright">
          <feFuncR type="linear" slope="1.08" />
          <feFuncG type="linear" slope="1.08" />
          <feFuncB type="linear" slope="1.08" />
        </feComponentTransfer>
        <feTurbulence type="fractalNoise" baseFrequency="0.016 0.012" numOctaves="2" seed="7" result="noise" />
        <feDisplacementMap in="bright" in2="noise" scale="5" xChannelSelector="R" yChannelSelector="G" />
      </filter>
    </defs>
  </svg>
);

// ---- Page Loader ----
const PageLoader = ({ onDone }) => {
  const [progress, setProgress] = React.useState(0);
  const [fading, setFading] = React.useState(false);

  React.useEffect(() => {
    let current = 0;
    let raf;
    let finished = false;

    const complete = () => {
      if (finished) return;
      finished = true;
      cancelAnimationFrame(raf);
      const rush = () => {
        current = Math.min(100, current + 4);
        setProgress(current);
        if (current < 100) requestAnimationFrame(rush);
        else setTimeout(() => { setFading(true); setTimeout(onDone, 500); }, 150);
      };
      requestAnimationFrame(rush);
    };

    const tick = () => {
      if (finished) return;
      const step = current < 30 ? 1.8 : current < 60 ? 0.9 : current < 80 ? 0.4 : 0.08;
      current = Math.min(88, current + step);
      setProgress(current);
      if (current < 88) raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);

    let pageLoaded = false, minElapsed = false;
    const tryComplete = () => { if (pageLoaded && minElapsed) complete(); };
    const onLoad = () => { pageLoaded = true; tryComplete(); };
    setTimeout(() => { minElapsed = true; tryComplete(); }, 3500);
    if (document.readyState === 'complete') onLoad();
    else window.addEventListener('load', onLoad, { once: true });

    return () => { cancelAnimationFrame(raf); window.removeEventListener('load', onLoad); };
  }, []);

  return (
    <div style={{
      position: 'fixed', inset: 0, zIndex: 99999,
      background: 'var(--paper)',
      display: 'flex', flexDirection: 'column',
      alignItems: 'center', justifyContent: 'center',
      gap: '24px',
      opacity: fading ? 0 : 1,
      transition: 'opacity 0.5s ease',
      pointerEvents: fading ? 'none' : 'all',
    }}>
      <img src="assets/logo.png" alt="Eu Faço Parte" style={{ width: '110px', height: 'auto' }} />
      <p style={{
        fontFamily: 'var(--mono)', fontSize: '11px',
        letterSpacing: '0.12em', textTransform: 'uppercase',
        color: 'var(--ink-3)', margin: 0,
      }}>{t('loader.msg')}</p>
      <div style={{
        width: '180px', height: '3px',
        background: 'var(--rule-strong)', borderRadius: '999px', overflow: 'hidden',
      }}>
        <div style={{
          height: '100%', width: `${progress}%`,
          background: 'var(--accent)', borderRadius: '999px',
          transition: 'width 80ms linear',
        }} />
      </div>
    </div>
  );
};

const App = () => {
  const [tweaks, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [donationOpen, setDonationOpen] = React.useState(false);
  const [loading, setLoading] = React.useState(true);

  React.useEffect(() => { applyTweaks(tweaks); }, [tweaks]);
  React.useEffect(() => { window.openDonationModal = () => setDonationOpen(true); }, []);

  return (
    <>
      {loading && <PageLoader onDone={() => setLoading(false)} />}
      <LiquidGlassFilter />
      <Nav />
      <TranslationBanner />
      <Hero />
      <Partners />
      <AcoesRecentes />
      <Announce />
      <ApoioProjetos />
      <BrasilMap />
      <Initiatives />
      <Stats />
      <AbrigoEducacao />
      <Protecao />
      <Conexao />
      <Manifesto />
      <Footer />

      {donationOpen && <DonationModal onClose={() => setDonationOpen(false)} />}

      <TweaksPanel title={t('tweaks.title')}>
        <TweakSection title={t('tweaks.accent')}>
          <div className="preset-row">
            {ACCENT_PRESETS.map(p => (
              <button
                key={p.name}
                className={`preset-swatch ${tweaks.accentHue === p.h && Math.abs(tweaks.accentLightness - p.l) < 0.01 ? 'active' : ''}`}
                onClick={() => setTweak({ accentHue: p.h, accentChroma: p.c, accentLightness: p.l })}
                title={p.name}
              >
                <span className="swatch-dot" style={{ background: `oklch(${p.l} ${p.c} ${p.h})` }}></span>
                <span className="swatch-name">{p.name}</span>
              </button>
            ))}
          </div>
          <TweakSlider label={t('tweaks.hue')} value={tweaks.accentHue} min={0} max={360} step={1}
            onChange={(v) => setTweak('accentHue', v)} />
          <TweakSlider label={t('tweaks.sat')} value={tweaks.accentChroma} min={0} max={0.2} step={0.005}
            onChange={(v) => setTweak('accentChroma', v)} />
          <TweakSlider label={t('tweaks.light')} value={tweaks.accentLightness} min={0.2} max={0.7} step={0.01}
            onChange={(v) => setTweak('accentLightness', v)} />
        </TweakSection>

        <TweakSection title={t('tweaks.paper')}>
          <TweakSlider label={t('tweaks.warmth')} value={tweaks.paperWarmth} min={30} max={120} step={1}
            onChange={(v) => setTweak('paperWarmth', v)} />
          <TweakSlider label={t('tweaks.bright')} value={tweaks.paperLightness} min={0.92} max={0.99} step={0.005}
            onChange={(v) => setTweak('paperLightness', v)} />
        </TweakSection>

        <TweakSection title={t('tweaks.typo')}>
          <TweakSelect label={t('tweaks.serif')} value={tweaks.serif} options={SERIF_OPTIONS}
            onChange={(v) => setTweak('serif', v)} />
          <TweakSelect label={t('tweaks.sans')} value={tweaks.sans} options={SANS_OPTIONS}
            onChange={(v) => setTweak('sans', v)} />
          <TweakSelect label={t('tweaks.mono')} value={tweaks.mono} options={MONO_OPTIONS}
            onChange={(v) => setTweak('mono', v)} />
        </TweakSection>
      </TweaksPanel>
    </>
  );
};

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
