// Shared enquiry drawer + cart state, used by home and products pages.
// Exposes imperative API on window.EnquiryUI for non-React callers
// (e.g. CTAs in other components) and dispatches 'aquo:cart' events so
// nav cart counts can stay in sync.
function EnquiryDrawer() {
  const initial = (window.EnquiryCart && window.EnquiryCart.read()) || [];
  const initialOpen = typeof window !== 'undefined' && /[?&]openEnquiry=1\b/.test(window.location.search);
  const [cart, setCart] = React.useState(initial);
  const [drawer, setDrawer] = React.useState(initialOpen && initial.length > 0);
  const [toast, setToast] = React.useState('');
  const [justAdded, setJustAdded] = React.useState(null);
  const [form, setForm] = React.useState({ name: '', phone: '', email: '', message: '' });
  const [errors, setErrors] = React.useState({});
  const [sent, setSent] = React.useState(false);

  const enquiryEmail = (window.__AQUO_CONTENT__ && window.__AQUO_CONTENT__.enquiryEmail) || 'enquiries@aquo.co.za';

  React.useEffect(() => {
    if (window.EnquiryCart) window.EnquiryCart.write(cart);
    window.dispatchEvent(new CustomEvent('aquo:cart', { detail: cart }));
  }, [cart]);

  const add = React.useCallback((item) => {
    setCart(c => {
      const ex = c.find(x => x.id === item.id);
      if (ex) return c.map(x => x.id === item.id ? { ...x, qty: x.qty + 1 } : x);
      return [...c, { ...item, qty: 1 }];
    });
    setToast(`${item.name} added to enquiry`);
    setJustAdded(item.id);
    setTimeout(() => setToast(''), 2000);
    setTimeout(() => setJustAdded(null), 800);
  }, []);

  React.useEffect(() => {
    window.EnquiryUI = {
      add,
      open: () => setDrawer(true),
      close: () => setDrawer(false),
      addAndOpen: (item) => { add(item); setDrawer(true); },
      justAddedId: () => justAdded,
    };
    return () => { try { delete window.EnquiryUI; } catch (e) {} };
  }, [add, justAdded]);

  const updateQty = (id, d) =>
    setCart(c => c.map(x => x.id === id ? { ...x, qty: Math.max(0, x.qty + d) } : x).filter(x => x.qty > 0));
  const remove = (id) => setCart(c => c.filter(x => x.id !== id));
  const setField = (k, v) => {
    setForm(f => ({ ...f, [k]: v }));
    if (errors[k]) setErrors(e => ({ ...e, [k]: null }));
  };

  const validate = () => {
    const e = {};
    if (!form.name.trim()) e.name = 'Required';
    if (!form.phone.trim()) e.phone = 'Required';
    else if (!/^[\d\s+()\-]{7,}$/.test(form.phone.trim())) e.phone = 'Invalid phone';
    if (!form.email.trim()) e.email = 'Required';
    else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email.trim())) e.email = 'Invalid email';
    setErrors(e);
    return Object.keys(e).length === 0;
  };

  const count = cart.reduce((s, x) => s + x.qty, 0);
  const total = cart.reduce((s, x) => s + x.qty * (Number(x.price) || 0), 0);

  const [submitting, setSubmitting] = React.useState(false);

  const submitEnquiry = async (ev) => {
    ev.preventDefault();
    if (!validate() || submitting) return;
    setSubmitting(true);
    try {
      const r = await fetch('/umbraco/Surface/Enquiry/Submit', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          name: form.name,
          email: form.email,
          phone: form.phone,
          message: form.message,
          items: cart.map(x => ({ id: x.id, name: x.name, cat: x.cat, price: Number(x.price) || 0, qty: x.qty })),
          source: (typeof window !== 'undefined' && window.location.pathname.startsWith('/shop')) ? 'shop' : 'home',
        }),
      });
      const data = await r.json().catch(() => ({}));
      if (!r.ok || !data.ok) {
        setErrors(e => ({ ...e, _form: data.error || 'Could not send — please try again.' }));
        return;
      }
      setSent(true);
    } catch (_) {
      setErrors(e => ({ ...e, _form: 'Network error — please try again.' }));
    } finally {
      setSubmitting(false);
    }
  };

  const reset = () => {
    setCart([]); setSent(false);
    setForm({ name: '', phone: '', email: '', message: '' });
    setErrors({});
    setDrawer(false);
  };

  return (
    <React.Fragment>
      <div className={`drawer-backdrop${drawer ? ' open' : ''}`} onClick={() => setDrawer(false)} />
      <aside className={`drawer${drawer ? ' open' : ''}`}>
        <button className="drawer-close" onClick={() => setDrawer(false)} aria-label="Close">
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M6 6l12 12M18 6L6 18"/></svg>
        </button>

        {sent ? (
          <div className="sent">
            <div className="sent-icon">
              <svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><path d="M4 12l5 5L20 6"/></svg>
            </div>
            <h4>Enquiry sent</h4>
            <p>Thanks — your enquiry is in. Our team will reply within one business day.</p>
            <button className="sent-new" onClick={reset}>New enquiry</button>
          </div>
        ) : (
          <React.Fragment>
            <h3>Enquire about your selection</h3>
            <div className="drawer-sub">{count} {count === 1 ? 'item' : 'items'} · indicative R{total.toLocaleString()}</div>

            <div className="drawer-items">
              {cart.length === 0 ? (
                <div className="drawer-empty">No items yet.<br/>Tap <b>Add</b> on any product to build your enquiry.</div>
              ) : cart.map(x => (
                <div className="line" key={x.id}>
                  <div className="line-img">
                    {x.img ? (
                      <img src={x.img} alt=""/>
                    ) : (
                      <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" style={{ width: '60%', height: '60%', opacity: 0.7 }}>
                        <path d="M12 2l5 8a6 6 0 1 1-10 0l5-8z"/>
                      </svg>
                    )}
                  </div>
                  <div>
                    <div className="line-name">{x.name}</div>
                    <div className="line-meta">
                      <div className="qty">
                        <button onClick={() => updateQty(x.id, -1)}>−</button>
                        <span>{x.qty}</span>
                        <button onClick={() => updateQty(x.id, +1)}>+</button>
                      </div>
                      {x.cat && <span>{x.cat}</span>}
                    </div>
                    <a className="rm" onClick={() => remove(x.id)}>Remove</a>
                  </div>
                  <div className="line-price">R{((Number(x.price) || 0) * x.qty).toLocaleString()}</div>
                </div>
              ))}
            </div>

            {cart.length > 0 && (
              <form className="drawer-foot" onSubmit={submitEnquiry} noValidate>
                <div className="form-intro">
                  Prices are indicative. Send us your details and we'll confirm stock, delivery and final pricing by email — usually same day.
                </div>

                <div className="field">
                  <label>Your name <span className="req">*</span></label>
                  <input type="text" value={form.name} onChange={e => setField('name', e.target.value)} placeholder="Jane Mokoena"/>
                  {errors.name && <div className="form-err">{errors.name}</div>}
                </div>

                <div className="field-row">
                  <div className="field">
                    <label>Cell <span className="req">*</span></label>
                    <input type="tel" value={form.phone} onChange={e => setField('phone', e.target.value)} placeholder="082 123 4567"/>
                    {errors.phone && <div className="form-err">{errors.phone}</div>}
                  </div>
                  <div className="field">
                    <label>Email <span className="req">*</span></label>
                    <input type="email" value={form.email} onChange={e => setField('email', e.target.value)} placeholder="you@domain.co.za"/>
                    {errors.email && <div className="form-err">{errors.email}</div>}
                  </div>
                </div>

                <div className="field">
                  <label>Short message</label>
                  <textarea value={form.message} onChange={e => setField('message', e.target.value)} placeholder="Install location, water source, timeline, questions…" rows="3"/>
                </div>

                <div className="drawer-total">
                  <span className="label">Indicative total</span>
                  <span className="val">R{total.toLocaleString()}</span>
                </div>
                <button type="submit" className="checkout" disabled={submitting}>
                  {submitting ? 'Sending…' : 'Send enquiry'}
                  <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12h14M13 5l7 7-7 7"/></svg>
                </button>
                {errors._form && <div className="form-err" style={{ marginTop: 10 }}>{errors._form}</div>}
              </form>
            )}
          </React.Fragment>
        )}
      </aside>

      <div className={`toast${toast ? ' show' : ''}`}>✓ {toast}</div>
    </React.Fragment>
  );
}

window.EnquiryDrawer = EnquiryDrawer;
