// Contact page — form, what-happens-next timeline, response time, FAQ.

const { useState } = React;

// ─────────────────────────────────────────────────────────────────────────
// Web3Forms — drop your access key here.
// Get one free at https://web3forms.com → it ties the form to your email.
// Until a real key is set, submissions fall back to a local-only success
// state so the UI stays demo-able.
// ─────────────────────────────────────────────────────────────────────────
const WEB3FORMS_ACCESS_KEY = 'YOUR_WEB3FORMS_ACCESS_KEY';
const WEB3FORMS_ENDPOINT = 'https://api.web3forms.com/submit';

function Field({ label, required, hint, children }) {
  return (
    <label style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
      <span style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between' }}>
        <span>{label}{required && <span style={{ color: 'var(--ember)', marginLeft: 4 }}>*</span>}</span>
        {hint && <span className="mono" style={{ fontSize: 10, color: 'var(--muted)', letterSpacing: '0.06em' }}>{hint}</span>}
      </span>
      {children}
    </label>);

}

function ContactForm() {
  const isMobile = window.useIsMobile ? useIsMobile() : false;
  const [submitted, setSubmitted] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState(null);
  const [chip, setChip] = useState('Quick Wins · from $2,195');

  const onSubmit = async (e) => {
    e.preventDefault();
    setSubmitting(true);
    setError(null);

    const form = e.currentTarget;
    const data = new FormData(form);

    // Compose helpful metadata for the email subject + reply-to plumbing.
    const name = data.get('name') || 'a visitor';
    data.set('subject', `New project enquiry from ${name} · hyperfocusoz.com`);
    data.set('from_name', `HyperFocusOZ · ${name}`);
    if (data.get('email')) data.set('replyto', data.get('email'));

    // Honeypot — if filled, silently "succeed" so bots don't get feedback.
    if (data.get('botcheck')) {
      setTimeout(() => {setSubmitting(false);setSubmitted(true);}, 600);
      return;
    }

    // Demo / unconfigured fallback: no real submission until a real key is
    // set. Lets the page stay functional in mockups and previews.
    if (!WEB3FORMS_ACCESS_KEY || WEB3FORMS_ACCESS_KEY === 'YOUR_WEB3FORMS_ACCESS_KEY') {
      console.info('[contact form] Demo mode — no Web3Forms key set. Form data:', Object.fromEntries(data.entries()));
      setTimeout(() => {setSubmitting(false);setSubmitted(true);}, 700);
      return;
    }

    try {
      const res = await fetch(WEB3FORMS_ENDPOINT, {
        method: 'POST',
        body: data,
        headers: { Accept: 'application/json' }
      });
      const json = await res.json().catch(() => ({}));
      if (res.ok && json.success !== false) {
        setSubmitted(true);
      } else {
        setError(json.message || 'We couldn\'t send that just now. Please try again or email hello@hyperfocusoz.com directly.');
      }
    } catch (err) {
      setError('Network error. Please try again, or email hello@hyperfocusoz.com directly.');
    } finally {
      setSubmitting(false);
    }
  };

  if (submitted) {
    return (
      <FadeUp>
        <div style={{
          padding: 36, background: 'var(--paper)', borderRadius: 14,
          border: '1px solid var(--line)', display: 'flex', flexDirection: 'column', gap: 16
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
            <div style={{
              width: 48, height: 48, borderRadius: '50%', background: 'var(--ember)',
              display: 'flex', alignItems: 'center', justifyContent: 'center'
            }}>
              <svg width="22" height="22" viewBox="0 0 22 22" fill="none">
                <path d="M5 11.5L9.5 16L17 7" stroke="#fff" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round" />
              </svg>
            </div>
            <div>
              <div style={{ fontSize: 22, fontWeight: 800, letterSpacing: '-0.02em' }}>Got it — talk soon.</div>
              <div className="mono" style={{ fontSize: 11, color: 'var(--ember)', letterSpacing: '0.06em', marginTop: 3 }}>
                you'll hear back within 1 business day
              </div>
            </div>
          </div>
          <p style={{ fontSize: 15, lineHeight: 1.55, color: 'var(--muted)', margin: 0 }}>
            We've received your note and a senior practitioner will read it personally. Expect a reply with proposed times for a 30-minute discovery call — no slide decks, no sales pitch.
          </p>
          <Btn className="hf-btn" size="md" variant="ghost" onClick={() => setSubmitted(false)}>Send another message</Btn>
        </div>
      </FadeUp>);

  }

  return (
    <form onSubmit={onSubmit} style={{
      padding: isMobile ? 24 : 36, background: 'var(--bg-elevated)', borderRadius: 14,
      border: '1px solid var(--line)', display: 'flex', flexDirection: 'column', gap: 20,
      boxShadow: 'var(--shadow-card)'
    }}>
      {/* Hidden Web3Forms wiring */}
      <input type="hidden" name="access_key" value={WEB3FORMS_ACCESS_KEY} />
      {/* Honeypot — invisible to humans, filled by spam bots */}
      <input type="checkbox" name="botcheck" style={{ display: 'none' }} tabIndex="-1" autoComplete="off" aria-hidden="true" />

      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 4 }}>
        <div className="mono" style={{ fontSize: 11, letterSpacing: '0.18em', textTransform: 'uppercase', color: 'var(--muted)' }}>tell us about your project</div>
        <span className="mono" style={{ fontSize: 11, color: 'var(--ember)', letterSpacing: '0.06em' }}>// fields marked * are required</span>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : 'repeat(2, 1fr)', gap: 16 }}>
        <Field label="Your name" required><input type="text" name="name" placeholder="Alex Mercer" required /></Field>
        <Field label="Email" required><input type="email" name="email" placeholder="alex@company.com" required /></Field>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : 'repeat(2, 1fr)', gap: 16 }}>
        <Field label="Company"><input type="text" name="company" placeholder="Company name" /></Field>
        <Field label="Role"><input type="text" name="role" placeholder="Head of Engineering, Founder, …" /></Field>
      </div>

      <div>
        <div style={{ fontSize: 13, fontWeight: 600, marginBottom: 8 }}>What are you looking for?</div>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
          {['Quick Wins · from $2,195', 'Order to Cash', 'Procure to Pay', 'Lead to Customer', 'Hire to Retire', 'Record to Report', 'Service to Resolution', 'Not sure yet'].map((opt) =>
          <button key={opt} type="button" onClick={() => setChip(opt)} className="hf-btn" style={{
            padding: '8px 14px', borderRadius: 999,
            background: chip === opt ? 'var(--ink)' : 'transparent',
            color: chip === opt ? 'var(--bone)' : 'var(--ink)',
            border: chip === opt ? 'none' : '1px solid var(--line)',
            fontSize: 13, fontWeight: 500
          }}>
              {opt}
            </button>
          )}
        </div>
        {/* Hidden so the chip selection submits with the form */}
        <input type="hidden" name="service" value={chip} />
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : 'repeat(2, 1fr)', gap: 16 }}>
        <Field label="Timeline">
          <select name="timeline" defaultValue="This quarter">
            <option>This quarter</option>
            <option>Next quarter</option>
            <option>This year</option>
            <option>Exploring · no firm date</option>
          </select>
        </Field>
        <Field label="Budget range" hint="indicative only">
          <select name="budget" defaultValue="$25k – $75k">
            <option>Under $25k</option>
            <option>$25k – $75k</option>
            <option>$75k – $200k</option>
            <option>$200k+</option>
            <option>Not sure yet</option>
          </select>
        </Field>
      </div>

      <Field label="Tell us what you're trying to achieve" required hint="business outcome, not tech">
        <textarea name="message" placeholder="e.g. We process 800 customer-onboarding documents a week by hand and want to automate the first-pass review — accurately, with human approval before anything is filed." required />
      </Field>

      {error &&
      <div role="alert" style={{
        padding: '12px 14px', borderRadius: 8,
        background: 'rgba(168,58,42,0.10)', border: '1px solid rgba(168,58,42,0.3)',
        color: '#a83a2a', fontSize: 13, lineHeight: 1.5
      }}>
          {error}
        </div>
      }

      <div style={{
        display: 'flex',
        alignItems: isMobile ? 'stretch' : 'center',
        justifyContent: 'space-between',
        flexDirection: isMobile ? 'column' : 'row',
        gap: isMobile ? 14 : 0,
        marginTop: 4
      }}>
        <span className="mono" style={{ fontSize: 11, color: 'var(--fg-muted)', letterSpacing: '0.06em' }}>
          // your details stay private. read once, replied to personally.
        </span>
        <Btn className="hf-btn" size="lg" type="submit" disabled={submitting} style={{ alignSelf: isMobile ? 'flex-start' : 'auto' }}>
          {submitting ? 'Sending…' : 'Send message'} <Arrow />
        </Btn>
      </div>
    </form>);

}

function ContactSidebar() {
  const isMobile = window.useIsMobile ? useIsMobile() : false;
  return (
    <FadeUp delay={120}>
      <div style={{
        display: 'flex', flexDirection: 'column', gap: 24,
        position: isMobile ? 'static' : 'sticky', top: 100
      }}>

        {/* Response time card */}
        <div style={{ padding: 24, background: 'var(--bg-inverted)', color: 'var(--fg-on-inverted)', borderRadius: 14 }}>
          <div className="mono" style={{ fontSize: 11, letterSpacing: '0.18em', textTransform: 'uppercase', color: 'rgba(243,238,228,0.6)' }}>response time</div>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 10, marginTop: 10, flexWrap: 'wrap' }}>
            <span style={{ fontSize: 56, fontWeight: 800, letterSpacing: '-0.04em', lineHeight: 1 }}>1</span>
            <span style={{ fontSize: 22, fontWeight: 700, letterSpacing: '-0.02em', color: 'var(--ember)', whiteSpace: 'nowrap' }}>business day</span>
          </div>
          <p style={{ fontSize: 13, color: 'rgba(243,238,228,0.7)', lineHeight: 1.5, margin: '12px 0 0' }}>
            A senior practitioner reads every enquiry personally. No sales funnel, no auto-replies.
          </p>
        </div>

        {/* Direct details */}
        <div style={{ padding: 24, background: 'var(--paper)', borderRadius: 14, border: '1px solid var(--line)' }}>
          <div className="mono" style={{ fontSize: 11, letterSpacing: '0.18em', textTransform: 'uppercase', color: 'var(--muted)' }}>direct</div>

          {/* Book a call CTA — lives at the top of "direct" details */}
          <a
            href="#book"
            data-booking="discovery"
            className="hf-lift"
            style={{
              display: 'flex', alignItems: 'center', justifyContent: 'space-between',
              gap: 12, marginTop: 14, padding: '14px 16px',
              background: 'var(--ink)', color: 'var(--bone)',
              borderRadius: 10, textDecoration: 'none',
              border: '1px solid var(--ink)'
            }}>
            
            <span style={{ display: 'flex', flexDirection: 'column', gap: 2, minWidth: 0 }}>
              <span style={{ fontSize: 14, fontWeight: 700, letterSpacing: '-0.01em' }}>Book a 30-min discovery call

              </span>
              <span className="mono" style={{
                fontSize: 10, color: 'rgba(243,238,228,0.65)',
                letterSpacing: '0.06em'
              }}>
                pick a time · no charge
              </span>
            </span>
            <span style={{
              display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
              width: 28, height: 28, borderRadius: '50%', background: 'var(--ember)',
              color: '#fff', fontSize: 14, fontWeight: 700, flex: '0 0 auto'
            }}>→</span>
          </a>

          <div style={{ display: 'flex', flexDirection: 'column', gap: 14, marginTop: 18 }}>
            <DetailRow k="email" v={<a href="mailto:hello@hyperfocusoz.com" className="hf-ulink">hello@hyperfocusoz.com</a>} />
            <DetailRow k="office" v={<>HyperFocusOz Pty Ltd<br />Office 4509,<br />470 St Kilda Road<br />Melbourne VIC 3004</>} />
            <DetailRow k="hours" v="Mon–Fri · 8am–6pm AEST" />
            <DetailRow k="linkedin" v={<a href="#" className="hf-ulink">linkedin.com/company/hyperfocusoz</a>} />
          </div>
        </div>

        {/* Live status */}
        <div style={{ padding: '18px 22px', background: 'rgba(31,122,77,0.08)', borderRadius: 14, border: '1px solid rgba(31,122,77,0.2)', display: 'flex', alignItems: 'center', gap: 12 }}>
          <span className="hf-pulse" style={{ width: 8, height: 8, borderRadius: '50%', background: 'var(--ok)' }} />
          <div>
            <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--ok)' }}>Accepting Q3 engagements</div>
            <div className="mono" style={{ fontSize: 10, color: 'var(--muted)', letterSpacing: '0.06em', marginTop: 2 }}>2 of 4 lead slots available</div>
          </div>
        </div>
      </div>
    </FadeUp>);

}

function DetailRow({ k, v }) {
  return (
    <div style={{ display: 'flex', alignItems: 'baseline', gap: 12, paddingBottom: 10, borderBottom: '1px dashed var(--line)' }}>
      <span className="mono" style={{ fontSize: 10, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--muted)', minWidth: 60 }}>{k}</span>
      <span style={{ fontSize: 14, fontWeight: 500, flex: 1 }}>{v}</span>
    </div>);

}

function WhatHappensNext() {
  const isMobile = window.useIsMobile ? useIsMobile() : false;
  const steps = [
  { n: '01', t: 'You hit send', d: 'Your message lands directly in the lead\'s inbox — not a CRM queue.', when: 'now' },
  { n: '02', t: 'Personal reply', d: 'A senior practitioner reads it and replies with proposed times for a 30-min call.', when: '< 1 business day' },
  { n: '03', t: 'Discovery call', d: 'A conversation about your goals, constraints, stack. No slides. Honest answer on fit.', when: 'this week' },
  { n: '04', t: 'Written proposal', d: 'If we\'re the right team, you get a scoped, fixed-price proposal. If we\'re not, a recommendation.', when: 'within a week' }];

  return (
    <section style={{ background: 'var(--bg)', borderTop: '1px solid var(--line)' }}>
      <div className="container" style={{ padding: isMobile ? '64px 20px' : '96px 32px' }}>
        <FadeUp>
          <SectionLabel accent="02">What happens next</SectionLabel>
          <h2 style={{
            fontSize: 'clamp(30px, 5vw, 48px)',
            fontWeight: 800, letterSpacing: '-0.03em', lineHeight: 1.05,
            margin: '18px 0 48px', textWrap: 'balance', maxWidth: 760
          }}>
            From inbox to discovery call in <span style={{ color: 'var(--ember)' }}>under a week.</span>
          </h2>
        </FadeUp>

        <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : 'repeat(4, 1fr)', gap: isMobile ? 28 : 20, position: 'relative' }}>
          {!isMobile &&
          <div aria-hidden="true" style={{
            position: 'absolute', top: 24, left: 28, right: 28, height: 2,
            background: 'repeating-linear-gradient(90deg, var(--line) 0 8px, transparent 8px 14px)'
          }} />
          }
          {isMobile &&
          <div aria-hidden="true" style={{
            position: 'absolute', top: 24, bottom: 24, left: 23, width: 2,
            background: 'repeating-linear-gradient(180deg, var(--line) 0 8px, transparent 8px 14px)'
          }} />
          }
          {steps.map((s, i) =>
          <FadeUp key={s.n} delay={i * 90}>
              <div style={{
              display: 'flex',
              flexDirection: isMobile ? 'row' : 'column',
              gap: isMobile ? 16 : 14,
              alignItems: isMobile ? 'flex-start' : 'stretch'
            }}>
                <div style={{
                width: 48, height: 48, borderRadius: '50%', background: 'var(--bg-elevated)',
                border: '1px solid var(--line)', display: 'flex', alignItems: 'center', justifyContent: 'center',
                fontWeight: 800, fontSize: 15, letterSpacing: '-0.02em',
                position: 'relative', zIndex: 1, flex: '0 0 48px'
              }}>
                  {s.n}
                  <span className="hf-pulse" style={{ position: 'absolute', bottom: -3, right: -3, width: 10, height: 10, borderRadius: '50%', background: 'var(--ember)', border: '2px solid var(--bg)' }} />
                </div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 18, fontWeight: 700, letterSpacing: '-0.015em' }}>{s.t}</div>
                  <div className="mono" style={{ fontSize: 11, color: 'var(--ember)', letterSpacing: '0.08em', marginTop: 4 }}>{s.when}</div>
                  <p style={{ fontSize: 14, lineHeight: 1.55, color: 'var(--fg-muted)', margin: '8px 0 0', textWrap: 'pretty' }}>{s.d}</p>
                </div>
              </div>
            </FadeUp>
          )}
        </div>
      </div>
    </section>);

}

function FAQ() {
  const isMobile = window.useIsMobile ? useIsMobile() : false;
  const items = [
  { q: 'Do you only work with Australian businesses?', a: 'We\'re based in Melbourne and Sydney but work with teams in NZ, Asia, the UK, and US. AU-east time is our default, but we run async-first when timezones diverge.' },
  { q: 'What size projects do you take on?', a: 'Anything from a quick win to a 6-month build. We generally find customers like to put us to work with quick wins first and then as confidents builds, they ask us to tackle the bigger stuff.' },
  { q: 'Do you sign NDAs before discovery?', a: 'Of course. Send your NDA with your initial message, or use ours — happy with either.' },
  { q: 'What does pricing look like?', a: 'Up front pricing proposals where possible and if you want ongoing support, agreements can be made with monthly plans. Weekly retainer where scope is genuinely open-ended. Either way you see the number before you commit.' },
  { q: 'Can you work with our existing team?', a: 'Yes — we embed alongside in-house engineers all the time. We pair, we code-review, we do knowledge transfer as we go.' },
  { q: 'What if we don\'t know what we want yet?', a: 'Book the call anyway. Half of our discovery calls end with "you don\'t need us yet, here\'s what to do first." That answer is free.' }];

  return (
    <section style={{ background: 'var(--bg-alt)', borderTop: '1px solid var(--line)' }}>
      <div className="container" style={{ padding: isMobile ? '64px 20px' : '96px 32px' }}>
        <FadeUp>
          <div style={{
            display: 'grid',
            gridTemplateColumns: isMobile ? '1fr' : '1fr 1.6fr',
            gap: isMobile ? 28 : 64,
            alignItems: 'start'
          }}>
            <div>
              <SectionLabel accent="03">FAQ</SectionLabel>
              <h2 style={{
                fontSize: 'clamp(28px, 4.5vw, 40px)',
                fontWeight: 800, letterSpacing: '-0.025em', lineHeight: 1.05,
                margin: '18px 0 0', textWrap: 'balance'
              }}>
                Quick answers {isMobile ? '' : <br />}before you write.
              </h2>
              <p style={{ fontSize: 14, color: 'var(--fg-muted)', lineHeight: 1.55, margin: '18px 0 0', maxWidth: 320 }}>
                Don't see your question? Ask it in the form — we'd rather answer directly than guess.
              </p>
            </div>
            <div>
              {items.map((it, i) => <FAQItem key={i} {...it} defaultOpen={i === 0} />)}
            </div>
          </div>
        </FadeUp>
      </div>
    </section>);

}

function FAQItem({ q, a, defaultOpen = false }) {
  const [open, setOpen] = useState(defaultOpen);
  return (
    <div style={{ borderTop: '1px solid var(--line)' }}>
      <button onClick={() => setOpen((o) => !o)} style={{
        width: '100%', padding: '20px 0', background: 'transparent', border: 'none',
        display: 'flex', justifyContent: 'space-between', alignItems: 'center',
        textAlign: 'left', cursor: 'pointer'
      }}>
        <span style={{ fontSize: 18, fontWeight: 600, letterSpacing: '-0.015em', color: 'var(--ink)' }}>{q}</span>
        <span style={{
          width: 28, height: 28, borderRadius: '50%',
          border: '1px solid var(--line)', background: 'var(--paper)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          transition: 'transform .25s',
          transform: open ? 'rotate(45deg)' : 'rotate(0deg)'
        }}>
          <svg width="12" height="12" viewBox="0 0 12 12" fill="none">
            <path d="M6 1V11M1 6H11" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
          </svg>
        </span>
      </button>
      <div style={{
        overflow: 'hidden',
        maxHeight: open ? 240 : 0,
        opacity: open ? 1 : 0,
        transition: 'max-height .35s cubic-bezier(.2,.7,.2,1), opacity .25s'
      }}>
        <p style={{ fontSize: 15, lineHeight: 1.6, color: 'var(--muted)', margin: '0 0 22px', maxWidth: 640, textWrap: 'pretty' }}>{a}</p>
      </div>
    </div>);

}

function ContactApp() {
  const isMobile = window.useIsMobile ? useIsMobile() : false;
  return (
    <div>
      <TopNav active="contact" />
      <PageHero
        eyebrow="Get in touch"
        accent="//"
        title={<>Tell us what you're trying to <span style={{ color: 'var(--ember)' }}>achieve.</span></>}
        sub="Send a note and a senior practitioner will reply personally — usually within one business day. Either we're the right team and we propose a path forward, or we're not and we point you in the right direction." />
      
      <section style={{ background: 'var(--bg)' }}>
        <div className="container" style={{ padding: isMobile ? '48px 20px' : '64px 32px' }}>
          <div style={{
            display: 'grid',
            gridTemplateColumns: isMobile ? '1fr' : '1.6fr 1fr',
            gap: isMobile ? 32 : 56,
            alignItems: 'start'
          }}>
            <FadeUp><ContactForm /></FadeUp>
            <ContactSidebar />
          </div>
        </div>
      </section>
      <WhatHappensNext />
      <FAQ />
      <Footer />
    </div>);

}

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