/* Golden Circle website — shared parts (helpers, photographic placeholders).
   Loaded as a babel script; exports to window for the other kit scripts. */

const GC = window.GoldenCircleDesignSystem_b7b2f4 || {};

/* Eyebrow / billing label */
function Eyebrow({ children, tone = 'gold', style }) {
  const color = tone === 'gold' ? 'var(--gc-gold)'
    : tone === 'muted' ? 'var(--gc-stone-deep)'
    : tone === 'muted-dark' ? 'var(--gc-stone-soft)' : 'var(--gc-gold)';
  return (
    <p style={{ fontFamily: 'var(--font-billing)', fontSize: 12, fontWeight: 600,
      letterSpacing: '0.22em', textTransform: 'uppercase', color, margin: '0 0 18px', ...style }}>
      {children}
    </p>
  );
}

/* Brass hairline rule */
function Rule({ dark = false, style }) {
  return <hr style={{ border: 0, height: 1, background: 'var(--gc-brass)',
    opacity: dark ? 0.34 : 0.4, margin: 0, ...style }} />;
}

/* Warm, candle-lit photographic figure. Pass `src` for real photography;
   without it, renders an on-brand placeholder (vignette + ring watermark). */
function Figure({ ratio = '3 / 2', src, alt, position = 'center', label, caption, glow = '70% 80%', radius = 'var(--radius-md)', fill = false, className = '', style }) {
  return (
    <figure className={className} style={{ margin: 0, ...(fill ? { height: '100%', display: 'flex', flexDirection: 'column' } : {}) }}>
      <div style={{
        position: 'relative', borderRadius: radius, overflow: 'hidden',
        ...(fill ? { flex: 1, minHeight: 0 } : { aspectRatio: ratio }),
        background: `radial-gradient(130% 120% at 28% 18%, #2b2118 0%, #181209 60%, #110d07 100%)`,
        ...style,
      }}>
        {src ? (
          <img src={src} alt={alt || caption || ''}
            style={{ position: 'absolute', inset: 0, width: '100%', height: '100%',
              objectFit: 'cover', objectPosition: position, display: 'block' }} />
        ) : (
          <React.Fragment>
            {/* candle glow */}
            <div style={{ position: 'absolute', inset: 0,
              background: `radial-gradient(circle at ${glow}, rgba(201,174,118,0.30), rgba(184,155,94,0.06) 38%, transparent 60%)` }} />
            {/* grain */}
            <div style={{ position: 'absolute', inset: 0, opacity: 0.5, mixBlendMode: 'overlay',
              backgroundImage: "url(\"data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='120' height='120'><filter id='n'><feTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='2'/></filter><rect width='100%25' height='100%25' filter='url(%23n)' opacity='0.5'/></svg>\")" }} />
            {/* ring watermark */}
            <img src="assets/logos/symbol_gold.svg" alt="" aria-hidden="true"
              style={{ position: 'absolute', width: '34%', left: '50%', top: '50%',
                transform: 'translate(-50%,-50%)', opacity: 0.16 }} />
          </React.Fragment>
        )}
        {label && (
          <span style={{ position: 'absolute', left: 16, bottom: 14, fontFamily: 'var(--font-billing)',
            fontSize: 10.5, fontWeight: 600, letterSpacing: '0.2em', textTransform: 'uppercase',
            color: 'rgba(237,231,219,0.85)', textShadow: '0 1px 6px rgba(0,0,0,0.5)' }}>{label}</span>
        )}
      </div>
      {caption && (
        <figcaption style={{ fontFamily: 'var(--font-body)', fontSize: 13, color: 'var(--gc-stone-deep)',
          marginTop: 10 }}>{caption}</figcaption>
      )}
    </figure>
  );
}

/* The brass follow-spot ring behind the hero wordmark */
function FollowSpot({ size = 320, style }) {
  return (
    <img src="assets/logos/symbol_gold.svg" alt="" aria-hidden="true"
      style={{ width: size, height: size, ...style }} />
  );
}

/* Custom HTML dropdown (not the browser-default <select>). Keyboard accessible,
   token-styled, writes its value into a hidden input so a parent <form> picks it
   up via FormData. Works on light and dark surfaces. */
function CustomSelect({ name, label, options = [], placeholder = 'Choose one', defaultValue = '', onDark = false }) {
  const [open, setOpen] = React.useState(false);
  const [value, setValue] = React.useState(defaultValue);
  const [active, setActive] = React.useState(-1);
  const wrapRef = React.useRef(null);
  const btnRef = React.useRef(null);

  React.useEffect(() => {
    const onDoc = (e) => { if (wrapRef.current && !wrapRef.current.contains(e.target)) setOpen(false); };
    document.addEventListener('mousedown', onDoc);
    return () => document.removeEventListener('mousedown', onDoc);
  }, []);

  const choose = (v) => { setValue(v); setOpen(false); if (btnRef.current) btnRef.current.focus(); };
  const onKey = (e) => {
    if (e.key === 'ArrowDown') { e.preventDefault(); if (!open) { setOpen(true); setActive(0); } else setActive(a => Math.min(options.length - 1, a + 1)); }
    else if (e.key === 'ArrowUp') { e.preventDefault(); setActive(a => Math.max(0, a - 1)); }
    else if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); if (open && active >= 0) choose(options[active]); else setOpen(o => !o); }
    else if (e.key === 'Escape') { setOpen(false); }
  };

  const txt    = onDark ? 'var(--gc-footlight)' : 'var(--gc-score)';
  const muted  = onDark ? 'var(--gc-stone-soft)' : 'var(--gc-stone-deep)';
  const border = onDark ? 'var(--field-border-dark)' : 'var(--field-border)';
  const panel  = onDark ? 'var(--gc-charcoal)' : 'var(--gc-ivory)';
  const fieldBg = onDark ? 'rgba(255,255,255,0.04)' : 'var(--gc-ivory)';

  return (
    <div ref={wrapRef} style={{ position: 'relative', display: 'grid', gap: 7 }}>
      {label && <span style={{ fontFamily: 'var(--font-billing)', fontSize: 11, fontWeight: 600,
        letterSpacing: '0.14em', textTransform: 'uppercase', color: muted }}>{label}</span>}
      <input type="hidden" name={name} value={value} readOnly />
      <button ref={btnRef} type="button" aria-haspopup="listbox" aria-expanded={open} onClick={() => setOpen(o => !o)} onKeyDown={onKey}
        style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12, width: '100%',
          padding: '12px 14px', fontFamily: 'var(--font-body)', fontSize: 15, color: value ? txt : muted,
          background: fieldBg, border: `1px solid ${border}`, borderRadius: 'var(--radius-sm)', cursor: 'pointer', textAlign: 'left' }}>
        <span>{value || placeholder}</span>
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="var(--gc-gold)" strokeWidth="2"
          style={{ flex: 'none', transform: open ? 'rotate(180deg)' : 'none', transition: 'transform .2s ease' }}><path d="M6 9l6 6 6-6" /></svg>
      </button>
      {open && (
        <ul role="listbox" style={{ position: 'absolute', top: '100%', left: 0, right: 0, zIndex: 30, margin: '6px 0 0',
          padding: 6, listStyle: 'none', background: panel, border: `1px solid ${border}`, borderRadius: 'var(--radius-md)', boxShadow: 'var(--shadow-overlay)' }}>
          {options.map((opt, i) => (
            <li key={opt} role="option" aria-selected={value === opt} onMouseEnter={() => setActive(i)} onClick={() => choose(opt)}
              style={{ padding: '10px 12px', borderRadius: 'var(--radius-sm)', cursor: 'pointer', fontFamily: 'var(--font-body)',
                fontSize: 15, color: txt, background: active === i ? 'rgba(184,155,94,0.16)' : 'transparent' }}>
              {opt}
            </li>
          ))}
        </ul>
      )}
    </div>
  );
}

/* The enquiry form, wired to POST /api/enquiry. Used in both the Dialog and the
   footer. Honeypot + client validation; shows sending / success / error states. */
function EnquiryForm({ onDark = false, submitLabel = 'Send inquiry', onSuccess }) {
  const { Button, Input } = window.GoldenCircleDesignSystem_b7b2f4;
  const [status, setStatus] = React.useState('idle'); // idle | sending | ok | error
  const [error, setError] = React.useState('');

  async function submit(e) {
    e.preventDefault();
    const fd = new FormData(e.currentTarget);
    const payload = {
      name: (fd.get('name') || '').toString().trim(),
      email: (fd.get('email') || '').toString().trim(),
      brings: (fd.get('brings') || '').toString(),
      message: (fd.get('message') || '').toString().trim(),
      company: (fd.get('company') || '').toString(), // honeypot
    };
    if (!payload.name || !payload.email) { setError('Please add your name and email.'); setStatus('error'); return; }
    if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(payload.email)) { setError('Please enter a valid email address.'); setStatus('error'); return; }
    setStatus('sending'); setError('');
    try {
      const r = await fetch('/api/enquiry', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(payload) });
      const j = await r.json().catch(() => ({}));
      if (r.ok && j.ok) { setStatus('ok'); if (onSuccess) onSuccess(); }
      else if (r.status === 400 && j.error) { setStatus('error'); setError(j.error); }
      else { setStatus('error'); setError('We could not send that just now. Please email hello@goldencircleproductions.com directly.'); }
    } catch (_) {
      setStatus('error'); setError('Network problem. Please try again, or email hello@goldencircleproductions.com.');
    }
  }

  const muted = onDark ? 'var(--gc-stone-soft)' : 'var(--gc-stone-deep)';

  if (status === 'ok') {
    return (
      <div className="form-done" style={{ display: 'grid', gap: 10, padding: '6px 0' }}>
        <h3 style={{ fontFamily: 'var(--font-display)', fontWeight: 400, fontSize: 24,
          color: onDark ? 'var(--gc-footlight)' : 'var(--gc-score)', margin: 0 }}>Thank you — your note is on its way.</h3>
        <p style={{ fontFamily: 'var(--font-body)', fontSize: 15.5, lineHeight: 1.6, color: muted, margin: 0 }}>We reply within one business day.</p>
      </div>
    );
  }

  return (
    <form onSubmit={submit} noValidate style={{ display: 'grid', gap: 16 }}>
      <Input label="Name" name="name" placeholder="Your name" onDark={onDark} required />
      <Input label="Email" name="email" type="email" placeholder="name@domain.com" onDark={onDark} required />
      <CustomSelect name="brings" label="What brings you here" onDark={onDark}
        options={['Full management', 'Advisory', 'Not sure yet']} placeholder="Choose one" />
      <Input label="A short note (optional)" name="message" placeholder="Describe your concept and goals" onDark={onDark} />
      {/* honeypot — off-screen, not for human eyes */}
      <input type="text" name="company" tabIndex="-1" autoComplete="off" aria-hidden="true"
        style={{ position: 'absolute', left: '-9999px', width: 1, height: 1, opacity: 0 }} />
      {status === 'error' && (
        <p role="alert" style={{ fontFamily: 'var(--font-body)', fontSize: 14, color: 'var(--gc-velvet)', margin: 0 }}>{error}</p>
      )}
      <div>
        <Button variant="primary" type="submit" disabled={status === 'sending'}>
          {status === 'sending' ? 'Sending…' : submitLabel}
        </Button>
      </div>
    </form>
  );
}

Object.assign(window, { GC, Eyebrow, Rule, Figure, FollowSpot, CustomSelect, EnquiryForm });
