// FAQ, CTA (Formspree), Footer

function FAQ() {
  const items = [
    ["I'm not techy. Do I need to manage this?","No. We host it, we run it, we fix it. The automation lives on our infrastructure — you get the outputs (quotes in your CRM, SMS replies, booked jobs) without ever touching a dashboard. Your monthly retainer covers full support, monitoring and ongoing tweaks."],
    ['What CRMs and tools do you work with?','The trade favourites — SimPro, ServiceM8, Tradify, AroFlo, Fergus, Ascora — plus HubSpot, Pipedrive, Xero, MYOB, Jobber and plenty more. If it has an API or webhook, we can talk to it. If you\'re on SimPro, we\'ve done the whole end-to-end already.'],
    ['How much does it cost?','Most builds land between $2,000 and $10,000 AUD depending on scope. A missed-call text-back is cheap and fast; a full quoting + CRM integration is the upper end. After build you\'re on a monthly retainer covering hosting, monitoring, support and ongoing changes. The audit is free and you walk away with a fixed-price proposal.'],
    ['How long does it take?','Two to four weeks from signed proposal to live automation, for most jobs. We roll flows out one at a time so nothing goes dark on you mid-season.'],
    ['I\'m outside Cairns — does that matter?','Not even slightly. We\'re Cairns-based but work with trades Australia-wide. Everything happens over Zoom and Loom. Happy to do an in-person audit if you\'re in FNQ.'],
    ['Will this replace my office staff?','No — it lets them do the work they were hired for. Automation handles the repetitive bits (chasing, qualifying, building quotes). Your admin still approves quotes, talks to customers, handles the judgement calls.']
  ];
  const [open, setOpen] = React.useState(0);
  return (
    <section className="section section-ivory" id="faq">
      <div className="container">
        <div className="eyebrow">FAQ</div>
        <h2 className="display-h2">Straight answers, <span className="accent-italic accent-sun">no fluff.</span></h2>
        <div className="faq-wrap">
          {items.map(([q, a], i) => (
            <div key={i} className="faq-item" data-open={open === i}>
              <button className="faq-q" onClick={() => setOpen(open === i ? -1 : i)} aria-expanded={open === i}>
                <span>{q}</span>
                <span className="plus" aria-hidden="true">+</span>
              </button>
              <div className="faq-a">{a}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// --- Web3Forms contact form ---
const WEB3FORMS_KEY = "de2bcc7a-2529-4a85-97b2-63555105b399";
const WEB3FORMS_ENDPOINT = "https://api.web3forms.com/submit";

function CTA() {
  const [state, setState] = React.useState('idle'); // idle | sending | success | error
  const [error, setError] = React.useState('');
  const [ticketId] = React.useState(() => `NX-${Math.floor(10000 + Math.random() * 89999)}`);

  async function onSubmit(e) {
    e.preventDefault();
    const form = e.currentTarget;
    if (form.website.value) return; // honeypot
    setState('sending'); setError('');

    const data = new FormData(form);
    data.append('access_key', WEB3FORMS_KEY);
    data.append('subject', 'New audit request — northedgeautomations.com');
    data.append('from_name', 'NorthEdge Automations website');
    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) {
        setState('success');
      } else {
        setError(json.message || "Couldn't send — please try again or call Jarrah directly.");
        setState('error');
      }
    } catch (err) {
      setError("Couldn't reach the server. Check your connection and try again.");
      setState('error');
    }
  }

  return (
    <section className="section section-navy" id="contact">
      <div className="container">
        <div className="cta-grid">
          <div className="cta-copy">
            <div className="eyebrow">Book a free audit</div>
            <h2 className="display-h2">Let's find <span className="accent-italic accent-sun">where the leaks are.</span></h2>
            <p className="lead">
              45 minutes. No pitch deck. You'll walk away with a one-page map of where leads go,
              where time goes, and the two automations that would pay for themselves the fastest.
            </p>
            <div className="cta-links">
              <a href="tel:+61499885854" className="btn btn-primary">Call 0499 885 854 <span className="arrow">→</span></a>
              <a href="#form" className="btn btn-ghost">Or fill the form ↓</a>
            </div>
            <div className="cta-extras">
              <div className="cta-extra">
                <div className="ex-num">45<span style={{fontSize:20}}>min</span></div>
                <div className="ex-lbl">Audit call. Straight to the leaks. No slide deck, no tyre-kicking.</div>
              </div>
              <div className="cta-extra">
                <div className="ex-num">$0</div>
                <div className="ex-lbl">Cost of the audit. You walk away with the map even if we don't build.</div>
              </div>
            </div>
          </div>

          {state === 'success' ? (
            <div className="form-success">
              <div className="tick">✓</div>
              <h4>Booked <span className="accent-italic accent-sun">by smoko.</span></h4>
              <p style={{ color: 'var(--fg2)', fontSize: 15, lineHeight: 1.55, marginTop: 8 }}>
                We've got your details. Jarrah will text you back within the hour —
                no pitch deck, just a 45-min call and a map of where the leaks are.
              </p>
              <div className="ticket">Ticket · {ticketId} · {new Date().toLocaleString('en-AU', { hour: 'numeric', minute: '2-digit', hour12: true })}</div>
            </div>
          ) : (
            <form className="form-card" id="form" onSubmit={onSubmit} noValidate>
              <h4>Drop your details — we'll call back</h4>
              <div className="sub">Takes 30 seconds. We'll only use these to get hold of you for the audit.</div>
              {state === 'error' && <div className="form-error">{error}</div>}
              <div className="form-row two">
                <div>
                  <label htmlFor="name">Name</label>
                  <input id="name" name="name" required placeholder="Jarrah" autoComplete="name" />
                </div>
                <div>
                  <label htmlFor="phone">Phone</label>
                  <input id="phone" name="phone" required placeholder="0499 885 854" autoComplete="tel" type="tel" />
                </div>
              </div>
              <div className="form-row">
                <label htmlFor="email">Email</label>
                <input id="email" name="email" required type="email" placeholder="you@trade.com.au" autoComplete="email" />
              </div>
              <div className="form-row two">
                <div>
                  <label htmlFor="trade">Trade</label>
                  <select id="trade" name="trade" defaultValue="">
                    <option value="" disabled>Pick one…</option>
                    <option>Plumbing</option>
                    <option>Electrical</option>
                    <option>HVAC</option>
                    <option>Roofing</option>
                    <option>Fencing</option>
                    <option>Building</option>
                    <option>Landscaping</option>
                    <option>Other</option>
                  </select>
                </div>
                <div>
                  <label htmlFor="crm">Job management software (CRM)</label>
                  <select id="crm" name="crm" defaultValue="">
                    <option value="" disabled>Which one?</option>
                    <option>SimPro</option>
                    <option>ServiceM8</option>
                    <option>Tradify</option>
                    <option>AroFlo</option>
                    <option>Fergus</option>
                    <option>Ascora</option>
                    <option>None / spreadsheet</option>
                    <option>Other</option>
                  </select>
                </div>
              </div>
              <div className="form-row">
                <label htmlFor="pain">What's the one thing eating your time?</label>
                <textarea id="pain" name="message" rows="3" placeholder="Missed calls · quote backlog · SimPro chasing…" />
              </div>
              {/* Honeypot */}
              <div className="honeypot" aria-hidden="true">
                <label>Leave this blank</label>
                <input type="text" name="website" tabIndex="-1" autoComplete="off" />
              </div>
              {/* Web3Forms anti-bot: botcheck must remain empty */}
              <input type="checkbox" name="botcheck" style={{ display: 'none' }} tabIndex="-1" />
              <button
                type="submit"
                className="btn btn-accent"
                style={{ width: '100%', justifyContent: 'center', marginTop: 8 }}
                disabled={state === 'sending'}
              >
                {state === 'sending' ? 'Sending…' : <>Book my free audit <span className="arrow">→</span></>}
              </button>
              <div className="form-footnote">No pitch deck. 45-min call. We'll map where the leaks are.</div>
            </form>
          )}
        </div>
      </div>
    </section>
  );
}

function Footer() {
  return (
    <footer className="footer">
      <div className="container">
        <div className="footer-grid">
          <div>
            <div className="footer-logo">
              <img src="assets/logo-mark-ivory.png" alt="" className="footer-mark" />
              <span className="footer-wordmark">
                <span className="fw-top">NORTHEDGE</span>
                <span className="fw-rule" />
                <span className="fw-bot">AUTOMATIONS</span>
              </span>
            </div>
            <p className="footer-tag">Custom automations for Australian trades. Less admin, more work. Built in Cairns, FNQ.</p>
          </div>
          <div className="footer-col">
            <h5>Automations</h5>
            <a href="#services">Missed-call text-back</a>
            <a href="#services">AI receptionist</a>
            <a href="#services">Automated quoting</a>
            <a href="#services">Booking & scheduling</a>
            <a href="#services">Reporting dashboards</a>
          </div>
          <div className="footer-col">
            <h5>Company</h5>
            <a href="#problem">The leak</a>
            <a href="#process">Process</a>
            <a href="#case">Case study</a>
            <a href="#faq">FAQ</a>
          </div>
          <div className="footer-col">
            <h5>Get in touch</h5>
            <a href="tel:+61499885854">0499 885 854</a>
            <a href="#contact">Book a free audit →</a>
          </div>
        </div>
        <div className="footer-bottom">
          <span>© 2026 NorthEdge Automations · Cairns QLD · ABN 70 686 798 097</span>
          <span>Less admin. More work.</span>
        </div>
      </div>
    </footer>
  );
}

Object.assign(window, { FAQ, CTA, Footer });
