// Top-level app: orchestrates state, tweaks, sections.

// Supabase config — anon/publishable key is safe in the browser; RLS restricts to inserts only.
const SUPABASE_URL = 'https://yvlosiobmfmuzjfeegoq.supabase.co';
const SUPABASE_KEY = 'sb_publishable_kfOKmSVToDqcSn31tIR3RA_FdlIYdLE';

async function submitWaitlist({ email, role }) {
  const res = await fetch(`${SUPABASE_URL}/rest/v1/waitlist`, {
    method: 'POST',
    headers: {
      'apikey': SUPABASE_KEY,
      'Authorization': `Bearer ${SUPABASE_KEY}`,
      'Content-Type': 'application/json',
      'Prefer': 'return=minimal',
    },
    body: JSON.stringify({
      email,
      role,
      user_agent: navigator.userAgent,
      referrer: document.referrer || null,
    }),
  });
  if (!res.ok) {
    const text = await res.text();
    // Postgres unique-violation code = 23505
    if (res.status === 409 || text.includes('23505') || text.includes('duplicate')) {
      throw new Error('duplicate');
    }
    throw new Error(text || 'Submit failed');
  }
  return true;
}

const TWEAK_DEFAULTS = {
  "palette": "wheat",
  "density": "regular",
  "copyTone": "balanced",
  "showTicker": true
};

const PALETTES = {
  wheat: {
    '--paper': '#f5f1e6', '--paper-2': '#efe9d8', '--paper-3': '#e7dfca',
    '--line': 'rgba(45,33,16,0.12)', '--line-2': 'rgba(45,33,16,0.22)',
    '--ink': '#1d1709', '--ink-2': '#3a2f1c', '--ink-3': '#6b5a3c', '--ink-4': '#9a8a68',
    '--amber': '#c2730b', '--amber-2': '#e89020', '--amber-soft': '#f3d59a',
  },
  cream: {
    '--paper': '#faf6ec', '--paper-2': '#f3ecd9', '--paper-3': '#ebe1c4',
    '--line': 'rgba(45,33,16,0.10)', '--line-2': 'rgba(45,33,16,0.20)',
    '--ink': '#252012', '--ink-2': '#46392a', '--ink-3': '#7a6a4a', '--ink-4': '#a89878',
    '--amber': '#9a5d10', '--amber-2': '#c87a1f', '--amber-soft': '#ecd29a',
  },
  rye: {
    '--paper': '#1d1a13', '--paper-2': '#262218', '--paper-3': '#332d20',
    '--line': 'rgba(245,241,230,0.10)', '--line-2': 'rgba(245,241,230,0.20)',
    '--ink': '#f5f1e6', '--ink-2': '#d8cfb5', '--ink-3': '#a89878', '--ink-4': '#75674a',
    '--amber': '#e89020', '--amber-2': '#f5a836', '--amber-soft': '#7a4a10',
  },
};

function applyPalette(name) {
  const root = document.documentElement;
  const p = PALETTES[name] || PALETTES.wheat;
  for (const [k, v] of Object.entries(p)) root.style.setProperty(k, v);
}

function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [email, setEmail] = React.useState('');
  const [role, setRole] = React.useState('Grower');
  const [joined, setJoined] = React.useState(false);
  const [submitting, setSubmitting] = React.useState(false);
  const [error, setError] = React.useState(null);

  React.useEffect(() => { applyPalette(t.palette); }, [t.palette]);

  const scrollToCTA = () => {
    const el = document.getElementById('join');
    if (!el) return;
    const y = el.getBoundingClientRect().top + window.scrollY - 80;
    window.scrollTo({ top: y, behavior: 'smooth' });
    setTimeout(() => document.querySelector('.cta-form input')?.focus(), 600);
  };

  const onJoin = async () => {
    if (submitting) return;
    // If no valid email, scroll the user to the form.
    if (!email || !/\S+@\S+\.\S+/.test(email)) {
      scrollToCTA();
      return;
    }
    setError(null);
    setSubmitting(true);
    try {
      await submitWaitlist({ email: email.trim().toLowerCase(), role });
      setJoined(true);
      setTimeout(() => {
        document.getElementById('join')?.scrollIntoView({ behavior: 'smooth', block: 'center' });
      }, 50);
    } catch (e) {
      if (e.message === 'duplicate') {
        // Treat duplicate as success — user is already on the list.
        setJoined(true);
      } else {
        console.error('Waitlist submit failed', e);
        setError("Couldn't sign you up — try again in a sec.");
      }
    } finally {
      setSubmitting(false);
    }
  };

  const { Nav, Hero, SellerBuyer, Features, Proof, CTA, Footer } = window.Sections;
  const Ticker = window.Ticker;
  const Pricing = window.Pricing;

  return (
    <>
      <Nav onJoin={onJoin} />
      {t.showTicker && <Ticker />}
      <Hero onJoin={onJoin} copyTone={t.copyTone} density={t.density} />
      <SellerBuyer />
      <Features />
      <Pricing onJoin={onJoin} />
      <Proof />
      <CTA joined={joined} onJoin={onJoin} email={email} setEmail={setEmail} role={role} setRole={setRole} submitting={submitting} error={error} />
      <Footer />

      <TweaksPanel title="Tweaks">
        <TweakSection label="Palette" />
        <TweakRadio
          label="Theme"
          value={t.palette}
          options={[
            { value: 'wheat', label: 'Wheat' },
            { value: 'cream', label: 'Cream' },
            { value: 'rye',   label: 'Rye (dark)' },
          ]}
          onChange={(v) => setTweak('palette', v)}
        />
        <TweakSection label="Copy" />
        <TweakRadio
          label="Tone"
          value={t.copyTone}
          options={[
            { value: 'technical',    label: 'Technical' },
            { value: 'balanced',     label: 'Balanced' },
            { value: 'approachable', label: 'Plain' },
          ]}
          onChange={(v) => setTweak('copyTone', v)}
        />
        <TweakSection label="Layout" />
        <TweakToggle label="Show ticker tape" value={t.showTicker} onChange={(v) => setTweak('showTicker', v)} />
      </TweaksPanel>
    </>
  );
}

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