// Bee Blossom — Alcohol Calculator + Contact Form

// ── Calculator ──────────────────────────────────────────
// Drinks-per-hour by intensity (industry rule-of-thumb)
const INTENSITY = {
  light:  { rate: 1.0, label: "Light",  note: "1 drink / hour" },
  medium: { rate: 1.5, label: "Medium", note: "1.5 drinks / hour" },
  heavy:  { rate: 2.0, label: "Heavy",  note: "2 drinks / hour" },
};

// Drinks per unit & approximate retail price per unit
const UNITS = {
  cocktail: { drinksPerUnit: 16, unitLabel: "bottle of spirit (750ml)", pricePerUnit: 32 },
  wine:     { drinksPerUnit: 5,  unitLabel: "bottle of wine (750ml)",    pricePerUnit: 18 },
  beer:     { drinksPerUnit: 1,  unitLabel: "can/bottle of beer (12oz)", pricePerUnit: 4 },
};

function clamp(v, lo, hi) { return Math.max(lo, Math.min(hi, v)); }

function calcResults(guests, hours, intensity, mix) {
  const totalDrinks = Math.ceil(guests * hours * INTENSITY[intensity].rate);
  // Normalize mix to 100
  const sum = mix.cocktail + mix.wine + mix.beer || 1;
  const breakdown = {};
  let totalPrice = 0;
  for (const k of ["cocktail", "wine", "beer"]) {
    const drinks = Math.ceil(totalDrinks * (mix[k] / sum));
    const units = Math.ceil(drinks / UNITS[k].drinksPerUnit);
    // Add ~12% buffer & round to nice number for cost
    const cost = units * UNITS[k].pricePerUnit;
    breakdown[k] = { drinks, units, cost };
    totalPrice += cost;
  }
  // Service fee + buffer
  const service = Math.round(totalPrice * 0.18);
  return { totalDrinks, breakdown, totalPrice, service, total: totalPrice + service };
}

function Calculator({ imageryStyle }) {
  const [guests, setGuests] = React.useState(80);
  const [hours, setHours] = React.useState(4);
  const [intensity, setIntensity] = React.useState("medium");
  const [mix, setMix] = React.useState({ cocktail: 50, wine: 30, beer: 20 });

  const r = calcResults(guests, hours, intensity, mix);
  const setMixKey = (k, v) => setMix(prev => ({ ...prev, [k]: clamp(v, 0, 100) }));

  return (
    <div className="bb-calc">
      <div>
        <div className="bb-calc-field">
          <div className="bb-calc-field-head">
            <label htmlFor="guests">Guest count</label>
            <span className="bb-calc-value">{guests}</span>
          </div>
          <input id="guests" className="bb-slider" type="range" min="10" max="300" step="5"
                 value={guests} onChange={(e) => setGuests(Number(e.target.value))} />
        </div>

        <div className="bb-calc-field">
          <div className="bb-calc-field-head">
            <label htmlFor="hours">Event duration</label>
            <span className="bb-calc-value">{hours} hrs</span>
          </div>
          <input id="hours" className="bb-slider" type="range" min="1" max="8" step="0.5"
                 value={hours} onChange={(e) => setHours(Number(e.target.value))} />
        </div>

        <div className="bb-calc-field">
          <div className="bb-calc-field-head">
            <label>Drinker intensity</label>
            <span className="bb-calc-value">{INTENSITY[intensity].note}</span>
          </div>
          <div className="bb-segmented" role="tablist">
            {Object.entries(INTENSITY).map(([k, v]) => (
              <button key={k} type="button"
                      aria-pressed={intensity === k}
                      onClick={() => setIntensity(k)}>{v.label}</button>
            ))}
          </div>
        </div>

        <div className="bb-calc-field">
          <div className="bb-calc-field-head">
            <label>Drink mix</label>
            <span className="bb-calc-value">{mix.cocktail + mix.wine + mix.beer}%</span>
          </div>
          <div className="bb-mix-grid">
            {["cocktail", "wine", "beer"].map((k) => (
              <div className="bb-mix-row" key={k}>
                <span>{k}s · {mix[k]}%</span>
                <input className="bb-slider" type="range" min="0" max="100" step="5"
                       value={mix[k]} onChange={(e) => setMixKey(k, Number(e.target.value))} />
              </div>
            ))}
          </div>
        </div>
      </div>

      <div className="bb-results">
        <h4>Your estimate</h4>
        <div className="bb-results-total">
          ${r.total.toLocaleString()}<small>est. all-in</small>
        </div>
        <div style={{ fontSize: 13, opacity: 0.85, marginTop: -4 }}>
          {r.totalDrinks} drinks across {guests} guests · {hours} hr open bar
        </div>

        <div className="bb-results-breakdown">
          {[
            ["cocktail", "Signature cocktails"],
            ["wine", "Wine"],
            ["beer", "Beer"],
          ].map(([k, label]) => (
            <div className="bb-results-row" key={k}>
              <span className="label">{label}</span>
              <span className="qty">{r.breakdown[k].units} × {UNITS[k].unitLabel.split(" ")[0]}{r.breakdown[k].units !== 1 ? "s" : ""} · {r.breakdown[k].drinks} drinks</span>
              <span className="amt">${r.breakdown[k].cost}</span>
            </div>
          ))}
          <div className="bb-results-row" style={{ opacity: 0.85, paddingTop: 6 }}>
            <span className="label">Service & gratuity</span>
            <span className="qty">18% included</span>
            <span className="amt">${r.service}</span>
          </div>
        </div>

        <p className="bb-results-note">
          Estimates use 1.5 oz cocktails, 5 oz wine pours and 12 oz beers. We'll
          confirm exact quantities and finalize pricing after your consultation.
        </p>
      </div>
    </div>
  );
}

// ── Contact ──────────────────────────────────────────────
function ContactForm() {
  const [data, setData] = React.useState({
    name: "", email: "", phone: "",
    eventType: "Wedding", date: "", guests: "",
    location: "", message: "",
  });
  const [errors, setErrors] = React.useState({});
  const [sent, setSent] = React.useState(false);
  const [sending, setSending] = React.useState(false);
  const [submitError, setSubmitError] = React.useState("");

  const update = (k, v) => {
    setData(d => ({ ...d, [k]: v }));
    if (errors[k]) setErrors(e => { const c = { ...e }; delete c[k]; return c; });
    if (submitError) setSubmitError("");
  };

  const submit = async (e) => {
    e.preventDefault();
    setSubmitError("");
    const errs = {};
    if (!data.name.trim()) errs.name = "Required";
    if (!data.email.trim()) errs.email = "Required";
    else if (!/^\S+@\S+\.\S+$/.test(data.email)) errs.email = "Invalid email";
    if (!data.date) errs.date = "Pick a date";
    if (!data.guests) errs.guests = "How many?";
    setErrors(errs);
    if (Object.keys(errs).length === 0) {
      setSending(true);
      try {
        const response = await fetch("/api/inquiries", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify(data),
        });
        const result = await response.json().catch(() => ({}));

        if (!response.ok) {
          if (result.errors) setErrors(result.errors);
          setSubmitError(result.message || "We couldn't send that inquiry. Please try again.");
          return;
        }

        setSent(true);
      } catch (error) {
        setSubmitError("We couldn't reach the server. Please try again.");
      } finally {
        setSending(false);
      }
    }
  };

  if (sent) {
    return (
      <form className="bb-form">
        <div className="bb-form-success">
          <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5">
            <circle cx="12" cy="12" r="10" />
            <path d="M8 12l3 3 5-6" strokeLinecap="round" strokeLinejoin="round" />
          </svg>
          <h4>Thank you, {data.name.split(" ")[0]}.</h4>
          <p>Your inquiry is in. We'll reach out within one business day to start designing your bar.</p>
          <button type="button" className="bb-cta bb-cta-ghost" style={{ marginTop: 12 }}
                  onClick={() => { setSent(false); setData({ name: "", email: "", phone: "", eventType: "Wedding", date: "", guests: "", location: "", message: "" }); }}>
            Send another inquiry
          </button>
        </div>
      </form>
    );
  }

  return (
    <form className="bb-form" onSubmit={submit} noValidate>
      <div className="bb-form-row">
        <div className={`bb-input ${errors.name ? "error" : ""}`}>
          <label>Your name</label>
          <input type="text" value={data.name} onChange={(e) => update("name", e.target.value)} placeholder="Jane Honeysworth" />
          {errors.name && <small>{errors.name}</small>}
        </div>
        <div className={`bb-input ${errors.email ? "error" : ""}`}>
          <label>Email</label>
          <input type="email" value={data.email} onChange={(e) => update("email", e.target.value)} placeholder="jane@example.com" />
          {errors.email && <small>{errors.email}</small>}
        </div>
      </div>

      <div className="bb-form-row">
        <div className="bb-input">
          <label>Phone (optional)</label>
          <input type="tel" value={data.phone} onChange={(e) => update("phone", e.target.value)} placeholder="(555) 123-4567" />
        </div>
        <div className="bb-input">
          <label>Event type</label>
          <select value={data.eventType} onChange={(e) => update("eventType", e.target.value)}>
            <option>Wedding</option>
            <option>Corporate / launch</option>
            <option>Private party</option>
            <option>Holiday gathering</option>
            <option>Other</option>
          </select>
        </div>
      </div>

      <div className="bb-form-row">
        <div className={`bb-input ${errors.date ? "error" : ""}`}>
          <label>Event date</label>
          <input type="date" value={data.date} onChange={(e) => update("date", e.target.value)} />
          {errors.date && <small>{errors.date}</small>}
        </div>
        <div className={`bb-input ${errors.guests ? "error" : ""}`}>
          <label>Guest count</label>
          <input type="number" min="10" max="500" value={data.guests} onChange={(e) => update("guests", e.target.value)} placeholder="80" />
          {errors.guests && <small>{errors.guests}</small>}
        </div>
      </div>

      <div className="bb-input">
        <label>Location / venue</label>
        <input type="text" value={data.location} onChange={(e) => update("location", e.target.value)} placeholder="Backyard, downtown loft, vineyard..." />
      </div>

      <div className="bb-input">
        <label>Tell us about your event</label>
        <textarea value={data.message} onChange={(e) => update("message", e.target.value)} placeholder="The vibe, menu ideas, or anything we should know." />
      </div>

      <div className="bb-form-actions">
        <small>{submitError || "We respond within one business day. No spam, just honey."}</small>
        <button type="submit" className="bb-cta bb-cta-accent" disabled={sending}>
          {sending ? "Sending..." : "Send inquiry"}
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
            <path d="M5 12h14M13 6l6 6-6 6" strokeLinecap="round" strokeLinejoin="round" />
          </svg>
        </button>
      </div>
    </form>
  );
}

Object.assign(window, { Calculator, ContactForm });
