// app.jsx — wires sections together with Tweaks panel + consultation modal
const { useState: useStateA, useEffect: useEffectA } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "palette": "orange-teal",
  "headlineVariant": "practical",
  "useSecondary": true
}/*EDITMODE-END*/;

// Palette presets. Orange is stronger / more saturated than the original Claude-adjacent
// burnt orange. Secondary is the cool counter-tone that gives premium balance.
const PALETTES = {
  'orange-teal':   { accent: '#D8541A', accent2: '#B0411A', secondary: '#1F4D44', secondary2: '#16382F', label: 'Orange · Deep Teal' },
  'orange-navy':   { accent: '#E25C1C', accent2: '#BA4818', secondary: '#1E2A44', secondary2: '#141C30', label: 'Orange · Ink Navy' },
  'orange-olive':  { accent: '#CC5018', accent2: '#A53E12', secondary: '#3F4A28', secondary2: '#2C351B', label: 'Amber · Olive' },
  'orange-plum':   { accent: '#E2541C', accent2: '#B5421A', secondary: '#3D2236', secondary2: '#291623', label: 'Orange · Aubergine' },
  'rust-stone':    { accent: '#A8401A', accent2: '#822F12', secondary: '#3A3A36', secondary2: '#262624', label: 'Rust · Stone' },
  'cinnabar-clay': { accent: '#EF4E1A', accent2: '#C53D14', secondary: '#5C3A2A', secondary2: '#412518', label: 'Cinnabar · Clay' },
};

function applyPalette(key) {
  const p = PALETTES[key] || PALETTES['orange-teal'];
  const r = document.documentElement.style;
  r.setProperty('--accent',      p.accent);
  r.setProperty('--accent-2',    p.accent2);
  r.setProperty('--secondary',   p.secondary);
  r.setProperty('--secondary-2', p.secondary2);
}

function ConsultModal({ open, onClose }) {
  const [form, setForm] = useStateA({ name: '', email: '', company: '', focus: 'Process automation', notes: '' });
  const [submitted, setSubmitted] = useStateA(false);
  const [loading, setLoading] = useStateA(false);
  const [error, setError] = useStateA('');

  useEffectA(() => {
    if (!open) { setSubmitted(false); setError(''); return; }
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [open]);

  if (!open) return null;

  const set = (k) => (e) => setForm({ ...form, [k]: e.target.value });

  return (
    <div style={{
      position: 'fixed', inset: 0, zIndex: 100,
      background: 'rgba(31,31,28,0.45)',
      backdropFilter: 'blur(6px)',
      display: 'grid', placeItems: 'center', padding: 24,
      animation: 'fadeIn .2s ease',
    }} onClick={onClose}>
      <div onClick={(e) => e.stopPropagation()} style={{
        width: '100%', maxWidth: 520,
        background: 'var(--bg)', borderRadius: 14,
        border: '1px solid var(--line-strong)',
        boxShadow: '0 30px 80px rgba(31,31,28,0.25)',
        overflow: 'hidden',
      }}>
        <div style={{padding: '22px 28px 18px', borderBottom: '1px solid var(--line)', display:'flex', alignItems:'center', justifyContent:'space-between'}}>
          <div>
            <div className="eyebrow">Book a consultation</div>
            <h3 style={{marginTop: 8, fontSize: 22, letterSpacing: '-0.02em'}}>30 minutes. No deck.</h3>
          </div>
          <button onClick={onClose} style={{
            border: 0, background: 'transparent', cursor: 'pointer',
            width: 32, height: 32, borderRadius: 8, color: 'var(--ink-2)',
            fontSize: 18,
          }}>×</button>
        </div>

        {!submitted ? (
          <form onSubmit={async (e) => {
            e.preventDefault();
            setLoading(true);
            setError('');
            try {
              const res = await fetch('/api/contact', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(form),
              });
              if (!res.ok) throw new Error('failed');
              setSubmitted(true);
            } catch {
              setError('Something went wrong. Please try again or email us directly.');
            } finally {
              setLoading(false);
            }
          }}
                style={{padding: '20px 28px 24px', display: 'flex', flexDirection: 'column', gap: 14}}>
            <Field label="Name" required value={form.name} onChange={set('name')} />
            <Field label="Work email" required type="email" value={form.email} onChange={set('email')} />
            <Field label="Company" value={form.company} onChange={set('company')} />
            <div style={{display: 'flex', flexDirection: 'column', gap: 6}}>
              <label className="mono" style={{fontSize: 11, letterSpacing: '0.06em', textTransform: 'uppercase', color: 'var(--ink-3)'}}>Primary focus</label>
              <select value={form.focus} onChange={set('focus')} style={inputStyle}>
                <option>Process automation</option>
                <option>Customer support workflows</option>
                <option>Internal operations</option>
                <option>Sales &amp; lead handling</option>
                <option>Reporting &amp; analytics</option>
                <option>Custom AI tools</option>
                <option>Cost reduction</option>
                <option>Not sure yet</option>
              </select>
            </div>
            <div style={{display: 'flex', flexDirection: 'column', gap: 6}}>
              <label className="mono" style={{fontSize: 11, letterSpacing: '0.06em', textTransform: 'uppercase', color: 'var(--ink-3)'}}>What&rsquo;s the situation? <span style={{color:'var(--ink-3)', textTransform:'none', letterSpacing: 0}}>(optional)</span></label>
              <textarea value={form.notes} onChange={set('notes')} rows={3} style={{...inputStyle, height: 'auto', padding: '10px 12px', resize: 'vertical', fontFamily: 'inherit'}} placeholder="A few sentences about where the work is" />
            </div>
            <div style={{display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: 10, gap: 12}}>
              <p style={{fontSize: 12, color: 'var(--ink-3)', maxWidth: 280, lineHeight: 1.5}}>
                We&rsquo;ll reply within one business day with a couple of times.
              </p>
              <button type="submit" className="btn btn-primary" style={{cursor: loading ? 'default' : 'pointer', opacity: loading ? 0.7 : 1}} disabled={loading}>
                {loading ? 'Sending…' : 'Send request'}
                {!loading && <IconArrow />}
              </button>
            </div>
            {error && (
              <p style={{fontSize: 13, color: '#c0392b', marginTop: 4}}>{error}</p>
            )}
          </form>
        ) : (
          <div style={{padding: '40px 28px 36px', textAlign: 'left'}}>
            <div style={{
              width: 36, height: 36, borderRadius: 99,
              display: 'grid', placeItems: 'center',
              background: 'rgba(199,107,42,0.12)', color: 'var(--accent)'
            }}>
              <IconCheck />
            </div>
            <h3 style={{marginTop: 18, fontSize: 22, letterSpacing: '-0.02em'}}>Got it. Talk soon.</h3>
            <p style={{marginTop: 10, color: 'var(--ink-2)', fontSize: 15, lineHeight: 1.55, maxWidth: 380}}>
              We&rsquo;ll be in touch at <strong style={{color: 'var(--ink)'}}>{form.email || 'your email'}</strong> within
              one business day with a couple of times that work.
            </p>
            <div style={{marginTop: 22}}>
              <button className="btn btn-ghost" onClick={onClose} style={{cursor: 'pointer'}}>Close</button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

const inputStyle = {
  height: 40, padding: '0 12px',
  border: '1px solid var(--line-strong)',
  borderRadius: 8,
  background: '#fff',
  color: 'var(--ink)',
  fontSize: 14,
  fontFamily: 'inherit',
  outline: 'none',
};

function Field({ label, required, type = 'text', value, onChange }) {
  return (
    <div style={{display: 'flex', flexDirection: 'column', gap: 6}}>
      <label className="mono" style={{fontSize: 11, letterSpacing: '0.06em', textTransform: 'uppercase', color: 'var(--ink-3)'}}>
        {label}{required && <span style={{color: 'var(--accent)', marginLeft: 4}}>*</span>}
      </label>
      <input required={required} type={type} value={value} onChange={onChange}
             style={inputStyle}
             onFocus={(e) => e.target.style.borderColor = 'var(--ink)'}
             onBlur={(e) => e.target.style.borderColor = 'var(--line-strong)'} />
    </div>
  );
}

function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  useEffectA(() => { applyPalette(t.palette); }, [t.palette]);
  useEffectA(() => {
    document.body.classList.toggle('use-secondary', !!t.useSecondary);
  }, [t.useSecondary]);

  // Trigger entry transitions once mounted.
  useEffectA(() => {
    requestAnimationFrame(() => {
      requestAnimationFrame(() => document.body.classList.add('has-loaded'));
    });
  }, []);

  // Scroll reveal: any element with .reveal gets .is-in once it enters the viewport.
  useEffectA(() => {
    const els = document.querySelectorAll('.reveal');
    if (!('IntersectionObserver' in window)) {
      els.forEach((el) => el.classList.add('is-in'));
      return;
    }
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting) {
          e.target.classList.add('is-in');
          io.unobserve(e.target);
        }
      });
    }, { rootMargin: '0px 0px -8% 0px', threshold: 0.08 });
    els.forEach((el) => io.observe(el));
    return () => io.disconnect();
  });

  const open = () => window.open('https://link.ikkosystems.com/widget/bookings/appointments-ikko', '_blank', 'noopener,noreferrer');

  return (
    <>
      <Nav onBookConsult={open} />
      <Hero
        headlineVariant={t.headlineVariant}
        onBookConsult={open}
      />
      <div className="reveal"><WhatWeDo onBookConsult={open} /></div>
      <div className="reveal"><HowWeWork /></div>
      <div className="reveal"><Results /></div>
      <div className="reveal"><About /></div>
      <FinalCTA onBookConsult={open} />
      <Footer onBookConsult={open} />

      <TweaksPanel>
        <TweakSection label="Palette" />
        <TweakSelect
          label="Color pair"
          value={t.palette}
          options={Object.entries(PALETTES).map(([value, p]) => ({ value, label: p.label }))}
          onChange={(v) => setTweak('palette', v)}
        />
        
        <TweakSection label="Hero" />
        <TweakRadio
          label="Headline"
          value={t.headlineVariant}
          options={[
            { value: 'practical',  label: 'Practical' },
            { value: 'measurable', label: 'Measurable' },
            { value: 'operators',  label: 'Operators' },
          ]}
          onChange={(v) => setTweak('headlineVariant', v)}
        />
       
      </TweaksPanel>
    </>
  );
}

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