// /brands and /clippers pages

const { useState: usePageState } = React;

function useIsMobile() {
  const [mobile, setMobile] = React.useState(() => window.innerWidth < 768);
  React.useEffect(() => {
    const handler = () => setMobile(window.innerWidth < 768);
    window.addEventListener('resize', handler);
    return () => window.removeEventListener('resize', handler);
  }, []);
  return mobile;
}

const HUES = {
  brands: {
    veil: 'rgba(20, 58, 110, 0.62)',
    glow: 'rgba(80, 140, 220, 0.18)',
    accent: '#5cb6d4',
    inkCard: '#143a52',
    formCard: '#ffffff',
    formInk: '#143a52',
    fieldUnderline: 'rgba(20,58,82,0.22)'
  },
  clippers: {
    veil: 'rgba(18, 70, 50, 0.62)',
    glow: 'rgba(100, 200, 140, 0.18)',
    accent: '#2f8a5e',
    inkCard: '#0f3a28',
    formCard: '#ffffff',
    formInk: '#0f3a28',
    fieldUnderline: 'rgba(15,58,40,0.22)'
  }
};

// ─── Supabase ─────────────────────────────────────────────────────────────────
const SUPABASE_URL      = 'https://iwlekqejrsbanesldrqs.supabase.co';
const SUPABASE_ANON_KEY = 'sb_publishable_1NikgR4dvMkMFWDKBHfmVw_Oeq8MU-F';
const db = supabase.createClient(SUPABASE_URL, SUPABASE_ANON_KEY);

// ─── Validation ───────────────────────────────────────────────────────────────
function validateEmail(v) {
  if (!v) return null;
  return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v.trim()) ? null : 'Enter a valid email address';
}

function validatePhone(v) {
  if (!v) return null;
  const digits = v.replace(/\D/g, '');
  if (digits.length < 7 || !/^[\+]?[\d\s\-\(\)\.]+$/.test(v.trim())) {
    return 'Enter a valid phone number';
  }
  return null;
}

// ─── Pages ────────────────────────────────────────────────────────────────────

function BrandsPage({ palette, onBack }) {
  return (
    <PageShell palette={palette} onBack={onBack} accent="brands" hue={HUES.brands}>
      <PageBody
        hue={HUES.brands}
        kicker="For brands · 001"
        headline={<>Be seen. Everywhere.<br />At once.</>}
        body={<>Your content should not die after one post.<br /><br />We take your long-form and turn it into clips that are cut and distributed by operators across the country.<br /><br />Your content shows up in corners of the internet it would never reach on your own, and it gets there faster than ever.</>}
        bullets={[
          'Your content distributed across hundreds of independent accounts.',
          'Reach audiences beyond your own following.',
          'Pay only for verified views — 100,000 views at the cost of a lunch.'
        ]}
        form={<BrandForm hue={HUES.brands} />}
      />
    </PageShell>
  );
}

function ClippersPage({ palette, onBack }) {
  return (
    <PageShell palette={palette} onBack={onBack} accent="clippers" hue={HUES.clippers}>
      <PageBody
        hue={HUES.clippers}
        kicker="For clippers · 002"
        headline={<>Your edits.<br />Their budgets.<br />Your bag.</>}
        body={<>We don't sit on briefs. We send drops — raw footage, brand context, a posting window — and you ship.<br /><br />Get paid per verified view, weekly, in plain numbers. The faster you cut, the more eyeballs you keep.</>}
        bullets={[
          'Highest, Most Competitive Payouts in the Industry',
          'Weekly payouts, no minimum',
          'First drop within 48h of approval'
        ]}
        form={<ClipperForm hue={HUES.clippers} />}
      />
    </PageShell>
  );
}

// ─── Layout ───────────────────────────────────────────────────────────────────

function PageShell({ palette, onBack, children, accent, hue }) {
  const isMobile = useIsMobile();
  return (
    <div style={{
      position: 'absolute', inset: 0,
      background: hue.veil,
      backdropFilter: 'blur(2px)', WebkitBackdropFilter: 'blur(2px)',
      zIndex: 50,
      display: 'flex', flexDirection: 'column',
      overflow: 'hidden',
      animation: 'pageFadeIn 600ms cubic-bezier(0.2, 0.8, 0.2, 1)'
    }}>
      <div style={{
        position: 'absolute', inset: 0,
        background: `radial-gradient(ellipse at 70% 50%, ${hue.glow} 0%, transparent 60%)`,
        pointerEvents: 'none'
      }} />

      {/* Nav */}
      <div style={{
        flexShrink: 0,
        display: 'flex', justifyContent: 'space-between', alignItems: 'center',
        padding: isMobile ? '16px 20px' : '20px 36px',
        color: '#ffffff',
        fontFamily: '"JetBrains Mono", monospace',
        fontSize: 12, letterSpacing: '0.16em', textTransform: 'uppercase',
        position: 'relative', zIndex: 1
      }}>
        <button
          onClick={onBack}
          style={{
            background: 'transparent', border: 'none', cursor: 'pointer',
            color: '#ffffff', font: 'inherit',
            display: 'flex', alignItems: 'center', gap: 10,
            padding: 0, letterSpacing: 'inherit'
          }}>
          <span style={{ display: 'inline-block', width: 18, height: 1, background: 'currentColor' }} />
          Back
        </button>
        {!isMobile && (
          <div style={{ opacity: 0.75 }}>
            Eyeballs · {accent === 'brands' ? '/for-brands' : '/for-clippers'}
          </div>
        )}
      </div>

      {/* Content — fills remaining height on desktop, natural scroll on mobile */}
      <div style={{
        flex: 1,
        minHeight: 0,
        padding: isMobile ? '0 20px 32px' : '0 48px 32px',
        display: 'flex',
        alignItems: isMobile ? 'flex-start' : 'stretch',
        overflowY: isMobile ? 'auto' : 'hidden',
        position: 'relative', zIndex: 1,
        WebkitOverflowScrolling: 'touch'
      }}>
        <div style={isMobile ? {
          width: '100%', maxWidth: 1200, margin: '0 auto'
        } : {
          flex: 1, minHeight: 0, display: 'flex', width: '100%', maxWidth: 1200, margin: '0 auto'
        }}>
          {children}
        </div>
      </div>
    </div>
  );
}

function PageBody({ hue, kicker, headline, body, bullets, form }) {
  const isMobile = useIsMobile();
  return (
    <div style={{
      ...(isMobile ? {
        display: 'flex',
        flexDirection: 'column',
        gap: 20
      } : {
        display: 'grid',
        gridTemplateColumns: '1.05fr 1fr',
        gridTemplateRows: '1fr',
        gap: 24,
        flex: 1,
        minHeight: 0
      }),
      alignItems: 'stretch',
      width: '100%'
    }}>
      {/* Left info card */}
      <div style={{
        background: hue.inkCard,
        color: '#ffffff',
        borderRadius: 6,
        padding: isMobile ? '32px 24px 28px' : '40px 44px 36px',
        display: 'flex',
        flexDirection: 'column',
        boxShadow: '0 24px 60px rgba(0,0,0,0.28)',
        minHeight: isMobile ? 'auto' : 0,
        position: 'relative',
        overflow: 'hidden'
      }}>
        <div style={{
          position: 'absolute', top: 0, left: 0,
          width: 64, height: 3, background: hue.accent
        }} />

        <div style={{
          fontFamily: '"JetBrains Mono", monospace',
          fontSize: 11, letterSpacing: '0.22em', textTransform: 'uppercase',
          opacity: 0.7
        }}>
          {kicker}
        </div>

        <h2 style={{
          fontFamily: '"Instrument Serif", serif',
          fontStyle: 'italic', fontWeight: 400,
          fontSize: isMobile ? 'clamp(36px, 9vw, 52px)' : 'clamp(36px, 3.4vw, 60px)',
          lineHeight: 1.0, letterSpacing: '-0.02em',
          margin: '14px 0 0'
        }}>
          {headline}
        </h2>

        <p style={{
          fontFamily: '"JetBrains Mono", monospace',
          fontSize: isMobile ? 12.5 : 12.5,
          lineHeight: 1.65,
          margin: isMobile ? '18px 0 0' : '20px 0 0',
          opacity: 0.88, maxWidth: 460
        }}>
          {body}
        </p>

        <div style={{ flex: 1, minHeight: isMobile ? 16 : 0 }} />

        <div style={{
          marginTop: isMobile ? 20 : 24,
          paddingTop: 16,
          borderTop: '1px solid rgba(255,255,255,0.12)'
        }}>
          <ul style={{
            listStyle: 'none', padding: 0, margin: 0,
            display: 'flex', flexDirection: 'column', gap: 10,
            fontFamily: '"JetBrains Mono", monospace', fontSize: 12
          }}>
            {bullets.map((b, i) => (
              <li key={i} style={{ display: 'flex', alignItems: 'flex-start', gap: 14 }}>
                <span style={{
                  marginTop: 5, width: 6, height: 6, borderRadius: '50%',
                  background: hue.accent, flexShrink: 0
                }} />
                <span style={{ opacity: 0.92, lineHeight: 1.5 }}>{b}</span>
              </li>
            ))}
          </ul>
        </div>
      </div>

      {/* Right form card — stretches to match left card via grid row */}
      <div style={{
        background: hue.formCard,
        color: hue.formInk,
        borderRadius: 6,
        padding: isMobile ? '28px 24px 24px' : '32px 28px 28px',
        boxShadow: '0 24px 60px rgba(0,0,0,0.28)',
        minHeight: isMobile ? 'auto' : 0,
        display: 'flex',
        flexDirection: 'column',
        overflow: 'hidden'
      }}>
        {form}
      </div>
    </div>
  );
}

// ─── Brand form ───────────────────────────────────────────────────────────────

function BrandForm({ hue }) {
  const [submitted, setSubmitted] = usePageState(false);
  const [loading, setLoading] = usePageState(false);
  const [form, setForm] = usePageState({ name: '', email: '', phone: '', instagram: '', youtube: '' });
  const [errors, setErrors] = usePageState({});

  function set(k, v) {
    setForm((p) => ({ ...p, [k]: v }));
    if (errors[k]) setErrors((p) => ({ ...p, [k]: null }));
  }

  async function handleSubmit(e) {
    e.preventDefault();
    const errs = {};
    const emailErr = validateEmail(form.email);
    const phoneErr = validatePhone(form.phone);
    if (emailErr) errs.email = emailErr;
    if (phoneErr) errs.phone = phoneErr;
    if (Object.keys(errs).length > 0) { setErrors(errs); return; }

    setLoading(true);
    try {
      await db.from('brand_enquiries').insert({
        name: form.name, email: form.email, phone: form.phone,
        instagram: form.instagram, youtube: form.youtube
      });
    } catch (_) {}
    setLoading(false);
    setSubmitted(true);
  }

  if (submitted) return <Submitted hue={hue} kind="brand" />;

  return (
    <form
      onSubmit={handleSubmit}
      style={{
        display: 'flex', flexDirection: 'column', gap: 10,
        color: hue.formInk, fontFamily: '"JetBrains Mono", monospace',
        flex: 1, overflow: 'visible'
      }}>
      <FormHeader hue={hue} kicker="Request a campaign">
        Tell us what you're<br />putting in front of people.
      </FormHeader>

      <CardField label="Your name" value={form.name} onChange={(v) => set('name', v)} hue={hue} />
      <CardField label="Email" value={form.email} onChange={(v) => set('email', v)} hue={hue} type="email" error={errors.email} />
      <CardField label="Phone number" value={form.phone} onChange={(v) => set('phone', v)} hue={hue} type="tel" placeholder="+91 555 123 4567" error={errors.phone} />
      <CardField label="Primary Instagram handle" value={form.instagram} onChange={(v) => set('instagram', v)} hue={hue} placeholder="@yourbrand" />
      <CardField label="Primary YouTube channel link" value={form.youtube} onChange={(v) => set('youtube', v)} hue={hue} placeholder="youtube.com/@yourbrand" />

      <div style={{ marginTop: 'auto', paddingTop: 12 }}>
        <SubmitButton hue={hue} disabled={loading}>{loading ? 'Sending…' : 'Get a proposal'}</SubmitButton>
      </div>
    </form>
  );
}

// ─── Clipper form ─────────────────────────────────────────────────────────────

function ClipperForm({ hue }) {
  const [submitted, setSubmitted] = usePageState(false);
  const [loading, setLoading] = usePageState(false);
  const [form, setForm] = usePageState({
    name: '', email: '', phone: '', instagram: '', youtube: '',
    workingWithOthers: null,
    otherAgency: ''
  });
  const [errors, setErrors] = usePageState({});

  function set(k, v) {
    setForm((p) => ({ ...p, [k]: v }));
    if (errors[k]) setErrors((p) => ({ ...p, [k]: null }));
  }

  async function handleSubmit(e) {
    e.preventDefault();
    const errs = {};
    const emailErr = validateEmail(form.email);
    const phoneErr = validatePhone(form.phone);
    if (emailErr) errs.email = emailErr;
    if (phoneErr) errs.phone = phoneErr;
    if (Object.keys(errs).length > 0) { setErrors(errs); return; }

    setLoading(true);
    try {
      await db.from('clipper_applications').insert({
        name: form.name, email: form.email, phone: form.phone,
        instagram: form.instagram, youtube: form.youtube,
        working_with_others: form.workingWithOthers,
        other_agency: form.otherAgency
      });
    } catch (_) {}
    setLoading(false);
    setSubmitted(true);
  }

  if (submitted) return <Submitted hue={hue} kind="clipper" />;

  return (
    <form
      onSubmit={handleSubmit}
      style={{
        display: 'flex', flexDirection: 'column', gap: 10,
        color: hue.formInk, fontFamily: '"JetBrains Mono", monospace',
        flex: 1, overflow: 'visible'
      }}>
      <FormHeader hue={hue} kicker="Apply to the network">
        Show us your eye.
      </FormHeader>

      <CardField label="Your name" value={form.name} onChange={(v) => set('name', v)} hue={hue} />
      <CardField label="Email" value={form.email} onChange={(v) => set('email', v)} hue={hue} type="email" error={errors.email} />
      <CardField label="Phone number (WhatsApp preferred)" value={form.phone} onChange={(v) => set('phone', v)} hue={hue} type="tel" placeholder="+91 555 123 4567" error={errors.phone} />
      <CardField
        label="Instagram handles — separate with commas"
        value={form.instagram}
        onChange={(v) => set('instagram', v)}
        hue={hue}
        placeholder="@handle1, @handle2, @handle3" />
      <CardField
        label="YouTube channel links — separate with commas"
        value={form.youtube}
        onChange={(v) => set('youtube', v)}
        hue={hue}
        placeholder="link1, link2, link3" />

      <YesNoField
        label="Currently working with other clipping agencies?"
        value={form.workingWithOthers}
        onChange={(v) => set('workingWithOthers', v)}
        hue={hue} />

      {form.workingWithOthers === true && (
        <CardField
          label="Which agency? (optional)"
          value={form.otherAgency}
          onChange={(v) => set('otherAgency', v)}
          hue={hue}
          placeholder="Agency name" />
      )}

      <div style={{ marginTop: 'auto', paddingTop: 12 }}>
        <SubmitButton hue={hue} disabled={loading}>{loading ? 'Sending…' : 'Apply to the network'}</SubmitButton>
      </div>
    </form>
  );
}

// ─── Form primitives ──────────────────────────────────────────────────────────

function FormHeader({ hue, kicker, children }) {
  const isMobile = useIsMobile();
  return (
    <div style={{ marginBottom: 4, flexShrink: 0 }}>
      <div style={{ fontSize: 11, letterSpacing: '0.22em', textTransform: 'uppercase', opacity: 0.55 }}>
        {kicker}
      </div>
      <div style={{
        fontFamily: '"Instrument Serif", serif', fontStyle: 'italic',
        fontSize: isMobile ? 'clamp(24px, 7vw, 32px)' : 'clamp(22px, 2.2vw, 32px)',
        lineHeight: 1.05, marginTop: 5,
        color: hue.formInk
      }}>
        {children}
      </div>
    </div>
  );
}

function CardField({ label, value, onChange, hue, type = 'text', textarea, placeholder, error }) {
  const [focus, setFocus] = usePageState(false);
  const Tag = textarea ? 'textarea' : 'input';
  return (
    <label style={{ display: 'flex', flexDirection: 'column', gap: 3, flexShrink: 0 }}>
      <span style={{
        fontSize: 9.5, letterSpacing: '0.22em', textTransform: 'uppercase',
        opacity: focus ? 0.85 : 0.55,
        transition: 'opacity 180ms'
      }}>{label}</span>
      <Tag
        type={type}
        value={value}
        onChange={(e) => onChange(e.target.value)}
        onFocus={() => setFocus(true)}
        onBlur={() => setFocus(false)}
        placeholder={placeholder}
        rows={textarea ? 2 : undefined}
        style={{
          font: 'inherit',
          fontFamily: '"JetBrains Mono", monospace',
          fontSize: 13,
          color: hue.formInk,
          background: 'transparent',
          border: 'none',
          borderBottom: `1px solid ${error ? '#e35d4e' : focus ? hue.accent : hue.fieldUnderline}`,
          padding: '4px 0 7px',
          outline: 'none', resize: 'none',
          transition: 'border-color 220ms',
          caretColor: hue.accent
        }} />
      {error && (
        <span style={{
          fontSize: 9, letterSpacing: '0.14em', textTransform: 'uppercase',
          color: '#e35d4e', marginTop: 1
        }}>{error}</span>
      )}
    </label>
  );
}

function YesNoField({ label, value, onChange, hue }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 6, flexShrink: 0 }}>
      <span style={{
        fontSize: 9.5, letterSpacing: '0.22em', textTransform: 'uppercase', opacity: 0.55
      }}>{label}</span>
      <div style={{ display: 'flex', gap: 8 }}>
        <YesNoChip label="Yes" active={value === true} onClick={() => onChange(true)} hue={hue} />
        <YesNoChip label="No" active={value === false} onClick={() => onChange(false)} hue={hue} />
      </div>
    </div>
  );
}

function YesNoChip({ label, active, onClick, hue }) {
  return (
    <button
      type="button"
      onClick={onClick}
      style={{
        flex: 1,
        background: active ? hue.inkCard : 'transparent',
        color: active ? '#ffffff' : hue.formInk,
        border: `1px solid ${active ? hue.inkCard : hue.fieldUnderline}`,
        borderRadius: 999,
        padding: '8px 14px',
        fontFamily: '"JetBrains Mono", monospace',
        fontSize: 11, letterSpacing: '0.16em', textTransform: 'uppercase',
        cursor: 'pointer',
        transition: 'background 180ms, border-color 180ms, color 180ms'
      }}>
      {label}
    </button>
  );
}

function SubmitButton({ hue, children, disabled }) {
  const [hover, setHover] = usePageState(false);
  return (
    <button
      type="submit"
      disabled={disabled}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      style={{
        background: hue.inkCard,
        color: '#ffffff',
        border: 'none',
        padding: '13px 22px',
        fontFamily: '"JetBrains Mono", monospace',
        fontSize: 11.5, letterSpacing: '0.18em', textTransform: 'uppercase',
        cursor: disabled ? 'default' : 'pointer',
        borderRadius: 999,
        alignSelf: 'flex-start',
        opacity: disabled ? 0.55 : 1,
        transition: 'transform 220ms cubic-bezier(0.2, 0.8, 0.2, 1), box-shadow 220ms, opacity 200ms',
        transform: (!disabled && hover) ? 'translateY(-2px)' : 'translateY(0)',
        boxShadow: (!disabled && hover) ? '0 6px 20px rgba(0,0,0,0.22)' : 'none'
      }}>
      {children}{!disabled && ' →'}
    </button>
  );
}

function Submitted({ hue, kind }) {
  const isMobile = useIsMobile();
  return (
    <div style={{
      color: hue.formInk, fontFamily: '"JetBrains Mono", monospace',
      flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'center'
    }}>
      <div style={{ fontSize: 11, letterSpacing: '0.22em', textTransform: 'uppercase', opacity: 0.6 }}>
        Received · 200 OK
      </div>
      <div style={{
        fontFamily: '"Instrument Serif", serif', fontStyle: 'italic',
        fontSize: isMobile ? 'clamp(36px, 9vw, 48px)' : 'clamp(36px, 3.6vw, 56px)',
        lineHeight: 1.0, marginTop: 16
      }}>
        We're watching.
      </div>
      <p style={{ fontSize: 13, lineHeight: 1.6, marginTop: 18, opacity: 0.85, maxWidth: 380 }}>
        {kind === 'brand'
          ? 'A campaign strategist will reach out inside 24 hours. Until then — keep the receipts ready.'
          : 'We review every application by hand. Expect to hear back within 48 hours.'}
      </p>
    </div>
  );
}

window.BrandsPage = BrandsPage;
window.ClippersPage = ClippersPage;
