// Booking widget, testimonials, FAQ, CTA, footer

// ============== BOOKING WIDGET ==============
function BookingWidget({ data }) {
  const [step, setStep] = React.useState(0);
  const [service, setService] = React.useState(null);
  const [urgency, setUrgency] = React.useState("scheduled");
  const [day, setDay] = React.useState(null);
  const [slot, setSlot] = React.useState(null);
  const [done, setDone] = React.useState(false);
  const widgetRef = React.useRef(null);

  // Build next 14 days starting today
  const today = new Date();
  const days = Array.from({ length: 14 }, (_, i) => {
    const d = new Date(today);
    d.setDate(today.getDate() + i);
    return d;
  });
  // Random-ish slot availability per day
  const slotAvailability = (date) => {
    const seed = date.getDate() + date.getMonth() * 31;
    const slots = ["8–10a", "10–12p", "12–2p", "2–4p", "4–6p"];
    return slots.map((s, i) => ({
      label: s,
      open: ((seed * 17 + i * 11) % 5) > 1,
    }));
  };

  const services = data.services.slice(0, 4).map((s) => s.t);

  const canSubmit = service && day !== null && slot !== null;

  const submit = () => {
    setDone(true);
    setStep(3);
  };

  const reset = () => {
    setStep(0);
    setService(null);
    setDay(null);
    setSlot(null);
    setUrgency("scheduled");
    setDone(false);
  };

  const dayLabel = day !== null ? days[day].toLocaleDateString(undefined, { weekday: "short", month: "short", day: "numeric" }) : "—";
  const slots = day !== null ? slotAvailability(days[day]) : [];

  // auto-advance step
  React.useEffect(() => {
    if (service && step === 0) setStep(1);
  }, [service]);
  React.useEffect(() => {
    if (day !== null && step === 1) setStep(2);
  }, [day]);

  return (
    <div className="widget" ref={widgetRef} id="book-widget">
      <div className="widget-head">
        <div className="t">Book a visit</div>
        <div className="step-dots">
          <span className={`step-dot ${step >= 0 ? "active" : ""} ${step > 0 ? "done" : ""}`}></span>
          <span className={`step-dot ${step >= 1 ? "active" : ""} ${step > 1 ? "done" : ""}`}></span>
          <span className={`step-dot ${step >= 2 ? "active" : ""} ${step > 2 ? "done" : ""}`}></span>
        </div>
      </div>

      {!done ? (
        <>
          {/* SUMMARY LINE */}
          <div className="summary-line">
            <span><span style={{opacity:0.6}}>Service · </span><span className="v">{service || "—"}</span></span>
            <span><span style={{opacity:0.6}}>Day · </span><span className="v">{dayLabel}</span></span>
            <span><span style={{opacity:0.6}}>Slot · </span><span className="v">{slot || "—"}</span></span>
          </div>

          {/* STEP 0: SERVICE */}
          <span className="field-label">01 · What do you need?</span>
          <div className="service-options">
            {services.map((s) => (
              <button
                key={s}
                className={`service-pill ${service === s ? "selected" : ""}`}
                onClick={() => setService(s)}
              >
                <span>{s}</span>
                <svg width="12" height="12" viewBox="0 0 12 12" fill="none">
                  <path d="M3 6h6M6 3l3 3-3 3" stroke="currentColor" strokeWidth="1.3" strokeLinecap="round"/>
                </svg>
              </button>
            ))}
          </div>

          {/* STEP 1: URGENCY + DAY */}
          <span className="field-label">02 · How soon?</span>
          <div className="urgency">
            <button className={urgency === "emergency" ? "selected" : ""} onClick={() => setUrgency("emergency")}>
              Emergency · today
            </button>
            <button className={urgency === "soon" ? "selected" : ""} onClick={() => setUrgency("soon")}>
              This week
            </button>
            <button className={urgency === "scheduled" ? "selected" : ""} onClick={() => setUrgency("scheduled")}>
              Anytime next 2 wks
            </button>
          </div>

          <div className="calendar">
            {["Mon","Tue","Wed","Thu","Fri","Sat","Sun"].map((d) => (
              <div key={d} className="cal-day head">{d}</div>
            ))}
            {/* leading empty cells to align by weekday */}
            {(() => {
              const first = days[0];
              const offset = (first.getDay() + 6) % 7; // Mon = 0
              return Array.from({ length: offset }, (_, i) => (
                <div key={"e"+i} className="cal-day disabled"></div>
              ));
            })()}
            {days.map((d, i) => {
              const avail = slotAvailability(d);
              const anyOpen = avail.some((a) => a.open);
              const isToday = i === 0;
              return (
                <button
                  key={i}
                  className={`cal-day ${day === i ? "selected" : ""} ${anyOpen ? "has-slots" : "disabled"}`}
                  onClick={() => { if (anyOpen) { setDay(i); setSlot(null); } }}
                  disabled={!anyOpen}
                >
                  <span className="dn">{d.toLocaleDateString(undefined, { month: "short" })}</span>
                  <span>{isToday ? "Today" : d.getDate()}</span>
                </button>
              );
            })}
          </div>

          {/* STEP 2: TIME SLOT */}
          <span className="field-label">03 · Pick a window</span>
          <div className="slots">
            {(slots.length ? slots : [{label:"—", open: false}, {label:"—", open: false}, {label:"—", open: false}, {label:"—", open: false}]).map((s, i) => (
              <button
                key={i}
                className={`slot-btn ${slot === s.label ? "selected" : ""}`}
                onClick={() => s.open && setSlot(s.label)}
                disabled={!s.open}
              >{s.label}</button>
            ))}
          </div>

          <button className="widget-cta" disabled={!canSubmit} onClick={submit}>
            {canSubmit ? "Confirm visit" : "Pick service, day, and time"}
            <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
              <path d="M3 7h8M8 4l3 3-3 3" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round"/>
            </svg>
          </button>

          <div className="widget-foot">
            <span>No payment to hold a slot</span>
            <span>$89 dispatch · credited to repair</span>
          </div>
        </>
      ) : (
        <div className="success-state">
          <div className="check">
            <svg width="24" height="24" viewBox="0 0 24 24" fill="none">
              <path d="M5 12.5L10 17L19 7.5" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
            </svg>
          </div>
          <h3>Locked in.</h3>
          <p>We'll text you the tech's photo and live ETA the moment we dispatch.</p>
          <div className="receipt">
            <div><span className="k">Reference · </span><span className="v">#HC-{Math.floor(Math.random()*90000)+10000}</span></div>
            <div><span className="k">Service · </span><span className="v">{service}</span></div>
            <div><span className="k">Window · </span><span className="v">{dayLabel} · {slot}</span></div>
            <div><span className="k">Dispatch · </span><span className="v">$89 (credited to repair)</span></div>
            <div><span className="k">Confirmation · </span><span className="v">SMS + email</span></div>
          </div>
          <button onClick={reset} className="btn-ghost" style={{marginTop:20}}>
            Book another visit
          </button>
        </div>
      )}
    </div>
  );
}

// ============== BOOKING SECTION ==============
function BookingSection({ data }) {
  return (
    <section className="section" id="book">
      <div className="container">
        <Reveal className="booking">
          <div className="booking-pitch">
            <span className="eyebrow">— Live booking</span>
            <h2>Three taps to a tech<br/>in your driveway.</h2>
            <p>No phone tag, no "we'll call you back," no surprise dispatch fees. Pick your service and window, and we'll send live updates from the truck to your phone.</p>
            <ul className="micro-list">
              <li><span className="dot"></span> Real availability — slots reserve the moment you tap.</li>
              <li><span className="dot"></span> Live ETA and tech photo sent by SMS on dispatch.</li>
              <li><span className="dot"></span> Pay nothing to hold the slot. $89 dispatch credited to any repair.</li>
              <li><span className="dot"></span> Reschedule or cancel by text up to 2 hours before.</li>
            </ul>
          </div>
          <BookingWidget data={data} />
        </Reveal>
      </div>
    </section>
  );
}

// ============== TESTIMONIALS ==============
const TESTIMONIALS = [
  {
    quote: "They showed up forty-five minutes after I called, walked me through every option on a tablet, and re-piped the whole laundry stack in an afternoon. The job site looked cleaner when they left than when they arrived.",
    name: "Diana M.",
    where: "Homeowner · Maplewood",
    photoLabel: "Replace — happy customer",
    stars: 5,
  },
  {
    quote: "I've used four companies in this valley over the last decade. Not even close. The transparency on pricing alone is worth the call. No clock games, no surprise add-ons, no upsell scripts.",
    name: "Rafael T.",
    where: "Repeat client · Eastlake",
    photoLabel: "Replace — repeat customer",
    stars: 5,
  },
  {
    quote: "Honest, fast, and properly licensed. They caught a slow leak the prior tech missed entirely and wrote up a five-year prevention plan I actually understood. This is who I send my mother to.",
    name: "Priya K.",
    where: "Property manager · Northwood",
    photoLabel: "Replace — partner",
    stars: 5,
  },
];

function Testimonials() {
  const [i, setI] = React.useState(0);
  const next = () => setI((p) => (p + 1) % TESTIMONIALS.length);
  const prev = () => setI((p) => (p - 1 + TESTIMONIALS.length) % TESTIMONIALS.length);

  // Auto-advance
  React.useEffect(() => {
    const id = setInterval(next, 7000);
    return () => clearInterval(id);
  }, []);

  return (
    <section className="section" id="reviews">
      <div className="container">
        <Reveal className="section-head">
          <span className="eyebrow">— What homeowners say</span>
          <h2>The receipts.</h2>
        </Reveal>
        <Reveal className="testimonials">
          <div className="testimonial-track">
            {TESTIMONIALS.map((t, idx) => (
              <div key={idx} className={`testimonial-card ${idx === i ? "active" : ""}`}>
                <div className="t-photo">
                  <span className="label">{t.photoLabel}</span>
                </div>
                <div>
                  <div className="t-stars">{"★".repeat(t.stars)}</div>
                  <blockquote className="t-quote" style={{marginTop:24}}>"{t.quote}"</blockquote>
                  <div className="t-attr">
                    <div className="who">
                      <strong>{t.name}</strong>
                      <div>{t.where}</div>
                    </div>
                  </div>
                </div>
              </div>
            ))}
          </div>
          <div className="t-nav">
            <span className="t-counter">{String(i+1).padStart(2,"0")} / {String(TESTIMONIALS.length).padStart(2,"0")}</span>
            <div className="t-nav-arrows">
              <button onClick={prev} aria-label="Previous">
                <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
                  <path d="M9 3L5 7l4 4" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round"/>
                </svg>
              </button>
              <button onClick={next} aria-label="Next">
                <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
                  <path d="M5 3l4 4-4 4" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round"/>
                </svg>
              </button>
            </div>
          </div>
        </Reveal>
      </div>
    </section>
  );
}

// ============== FAQ ==============
function FAQ({ data }) {
  const [open, setOpen] = React.useState(0);
  return (
    <section className="section" id="faq">
      <div className="container">
        <Reveal className="section-head">
          <span className="eyebrow">— Questions</span>
          <h2>The fine print,<br/>plainly written.</h2>
        </Reveal>
        <Reveal className="faq-list">
          {data.faqs.map((f, i) => (
            <div key={i} className={`faq-item ${open === i ? "open" : ""}`}>
              <button className="faq-q" onClick={() => setOpen(open === i ? -1 : i)}>
                <span>{f.q}</span>
                <span className="faq-toggle">
                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
                    <path d="M7 2v10M2 7h10" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round"/>
                  </svg>
                </span>
              </button>
              <div className="faq-a">
                <div className="faq-a-inner">{f.a}</div>
              </div>
            </div>
          ))}
        </Reveal>
      </div>
    </section>
  );
}

// ============== BIG CTA ==============
function BigCTA({ data }) {
  return (
    <div className="big-cta-wrap">
      <Reveal className="big-cta">
        <span className="eyebrow" style={{color:"rgba(255,255,255,0.6)"}}>— Ready when you are</span>
        <h2 style={{marginTop:24}}>The fix is one tap away.</h2>
        <p>Same-day dispatch across the valley. Licensed master technicians, flat-rate pricing, and a workmanship guarantee in writing.</p>
        <div className="actions">
          <a href="#book" className="btn-primary">{data.primaryCta}
            <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
              <path d="M3 8H13M13 8L8.5 3.5M13 8L8.5 12.5" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round"/>
            </svg>
          </a>
          <a href="tel:5550149920" className="btn-ghost-dark">
            <svg width="14" height="14" viewBox="0 0 16 16" fill="none">
              <path d="M3 3.5C3 3 3.5 2.5 4 2.5H5.5C6 2.5 6.4 2.8 6.5 3.2L7 5C7.1 5.4 7 5.8 6.7 6L5.7 7C6.5 8.5 7.5 9.5 9 10.3L10 9.3C10.2 9 10.6 8.9 11 9L12.8 9.5C13.2 9.6 13.5 10 13.5 10.5V12C13.5 12.5 13 13 12.5 13C7.3 13 3 8.7 3 3.5Z" stroke="currentColor" strokeWidth="1.2"/>
            </svg>
            {data.secondaryCta}
          </a>
        </div>
        <div className="meta-row">
          <div>
            <div className="meta-t">Hours</div>
            <div className="meta-v">24/7 emergency · Office 7a–7p</div>
          </div>
          <div>
            <div className="meta-t">Coverage</div>
            <div className="meta-v">35-mile radius of downtown</div>
          </div>
          <div>
            <div className="meta-t">License</div>
            <div className="meta-v">CCB #214887 · $2M insured</div>
          </div>
        </div>
      </Reveal>
    </div>
  );
}

// ============== FOOTER ==============
function Footer({ data }) {
  return (
    <footer className="footer">
      <div className="footer-top">
        <div>
          <div className="footer-mark">{data.brand}</div>
          <p className="footer-tag">{data.tagline}. Licensed master technicians, family-owned since 1998, and a workmanship guarantee in writing.</p>
        </div>
        <div>
          <h4>Services</h4>
          <ul>
            {data.services.slice(0,5).map((s,i)=>(<li key={i}><a href="#services">{s.t}</a></li>))}
          </ul>
        </div>
        <div>
          <h4>Company</h4>
          <ul>
            <li><a href="#process">Our process</a></li>
            <li><a href="#reviews">Reviews</a></li>
            <li><a href="#faq">FAQ</a></li>
            <li><a href="#book">Book a visit</a></li>
            <li><a href="#">Careers</a></li>
          </ul>
        </div>
        <div>
          <h4>Get in touch</h4>
          <ul>
            <li><a href="tel:5550149920">(555) 014-9920</a></li>
            <li><a href="mailto:hello@halden.co">hello@halden.co</a></li>
            <li><a href="#">1402 Industrial Way, Suite B</a></li>
            <li><a href="#">24/7 emergency line</a></li>
          </ul>
        </div>
      </div>
      <div className="footer-bottom">
        <span>© 2026 {data.brand} · CCB #214887 · BBB A+</span>
        <span>Designed by lotstech.services</span>
      </div>
    </footer>
  );
}

window.BookingWidget = BookingWidget;
window.BookingSection = BookingSection;
window.Testimonials = Testimonials;
window.FAQ = FAQ;
window.BigCTA = BigCTA;
window.Footer = Footer;
