/* global React, ReactDOM */
const { useState, useEffect } = React;

// Backend config (from config.js). Empty apiBase => demo mode, no network.
const API_BASE = (window.SHIFA_CONFIG && window.SHIFA_CONFIG.apiBase) || "";

// Bookable time slots — must match backend TIME_SLOTS (app/common.py) exactly.
const TIME_SLOTS = [
  "Morning (10am – 12pm)",
  "Afternoon (12pm – 4pm)",
  "Evening (4pm – 8pm)",
];

// ---------- Inline SVG icon set (all stroke, brand-cyan) ----------
const Ico = {
  Tooth: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" {...p}>
      <path d="M7 3.5C5 3.5 3.5 5 3.5 7.2c0 2.4 1 4 1.4 6 .3 1.5.4 3 .7 4.6.2 1.2.8 2.7 2 2.7 1.3 0 1.5-1.4 1.8-2.8.3-1.5.7-3.4 2.6-3.4s2.3 1.9 2.6 3.4c.3 1.4.5 2.8 1.8 2.8 1.2 0 1.8-1.5 2-2.7.3-1.6.4-3.1.7-4.6.4-2 1.4-3.6 1.4-6 0-2.2-1.5-3.7-3.5-3.7-1.4 0-2.4.7-3.4 1.3-.6.4-1.2.7-2.1.7s-1.5-.3-2.1-.7C9.4 4.2 8.4 3.5 7 3.5Z" />
    </svg>
  ),
  Implant: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" {...p}>
      <path d="M8 3h8l-1 5h-6L8 3Z" />
      <path d="M9 8h6v3l-1.5 2.5h-3L9 11V8Z" />
      <path d="M12 13.5V21" />
      <path d="M10.5 16h3M10 18.5h4" />
    </svg>
  ),
  Root: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" {...p}>
      <path d="M6 4h12v4H6z" />
      <path d="M9 8v6c0 2-1 4-1 6M15 8v6c0 2 1 4 1 6M12 8v12" />
    </svg>
  ),
  Sparkle: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" {...p}>
      <path d="M12 3v4M12 17v4M3 12h4M17 12h4M5.6 5.6l2.8 2.8M15.6 15.6l2.8 2.8M5.6 18.4l2.8-2.8M15.6 8.4l2.8-2.8" />
    </svg>
  ),
  Braces: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" {...p}>
      <rect x="3" y="9" width="18" height="6" rx="1.5" />
      <path d="M7 9v6M11 9v6M15 9v6M19 9v6M3 12h18" />
    </svg>
  ),
  Kid: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" {...p}>
      <circle cx="12" cy="8" r="4" />
      <path d="M5 21c0-3.9 3.1-7 7-7s7 3.1 7 7" />
      <circle cx="10.5" cy="8" r=".5" fill="currentColor" />
      <circle cx="13.5" cy="8" r=".5" fill="currentColor" />
      <path d="M10.5 10c.4.4 1 .6 1.5.6s1.1-.2 1.5-.6" />
    </svg>
  ),
  Shield: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" {...p}>
      <path d="M12 3 4 6v6c0 4.5 3.4 8 8 9 4.6-1 8-4.5 8-9V6l-8-3Z" />
      <path d="m9 12 2 2 4-4" />
    </svg>
  ),
  Phone: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" {...p}>
      <path d="M5 4h4l2 5-2.5 1.5a11 11 0 0 0 5 5L15 13l5 2v4a2 2 0 0 1-2 2A14 14 0 0 1 4 6a2 2 0 0 1 1-2Z" />
    </svg>
  ),
  Pin: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" {...p}>
      <path d="M12 21s7-6.5 7-12a7 7 0 0 0-14 0c0 5.5 7 12 7 12Z" />
      <circle cx="12" cy="9" r="2.5" />
    </svg>
  ),
  Clock: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" {...p}>
      <circle cx="12" cy="12" r="9" />
      <path d="M12 7v5l3 2" />
    </svg>
  ),
  Mail: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" {...p}>
      <rect x="3" y="5" width="18" height="14" rx="2" />
      <path d="m4 7 8 6 8-6" />
    </svg>
  ),
  Check: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round" {...p}>
      <path d="m5 12 5 5L20 7" />
    </svg>
  ),
  WA: (p) => (
    <svg viewBox="0 0 24 24" fill="currentColor" {...p}>
      <path d="M17.5 14.4c-.3-.1-1.7-.8-1.9-.9-.3-.1-.5-.1-.7.1-.2.3-.8.9-1 1.1-.2.2-.4.2-.7.1-.3-.1-1.3-.5-2.4-1.5-.9-.8-1.5-1.8-1.7-2.1-.2-.3 0-.5.1-.6.1-.1.3-.4.4-.5.1-.2.2-.3.3-.5.1-.2 0-.4 0-.5 0-.1-.7-1.7-1-2.4-.3-.6-.5-.5-.7-.5h-.6c-.2 0-.5.1-.8.4-.3.3-1 1-1 2.5s1.1 2.9 1.2 3.1c.1.2 2.1 3.2 5.1 4.5.7.3 1.3.5 1.7.6.7.2 1.4.2 1.9.1.6-.1 1.7-.7 2-1.4.2-.7.2-1.2.2-1.4 0-.1-.3-.2-.6-.3ZM12 2C6.5 2 2 6.5 2 12c0 1.8.5 3.5 1.3 4.9L2 22l5.3-1.4c1.4.8 3 1.2 4.7 1.2 5.5 0 10-4.5 10-10S17.5 2 12 2Zm0 18.2c-1.5 0-3-.4-4.3-1.2l-.3-.2-3.1.8.8-3-.2-.3c-.9-1.4-1.3-3-1.3-4.6 0-4.5 3.7-8.2 8.2-8.2 4.5 0 8.2 3.7 8.2 8.2.2 4.6-3.5 8.5-8 8.5Z" />
    </svg>
  ),
  Quote: (p) => (
    <svg viewBox="0 0 24 24" fill="currentColor" {...p}>
      <path d="M7 7h4v4H7c0 2 1 3 3 3v2c-3 0-5-2-5-5V7Zm9 0h4v4h-4c0 2 1 3 3 3v2c-3 0-5-2-5-5V7Z" />
    </svg>
  ),
  ArrowRight: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}>
      <path d="M5 12h14M13 6l6 6-6 6" />
    </svg>
  ),
  Calendar: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" {...p}>
      <rect x="3" y="5" width="18" height="16" rx="2" />
      <path d="M3 10h18M8 3v4M16 3v4" />
    </svg>
  ),
};

// ---------- Brand mark (recreated tooth + implant from logo) ----------
const BrandMark = ({ size = 44 }) => (
  <svg width={size} height={size} viewBox="0 0 64 64" fill="none">
    {/* outer cyan tooth */}
    <path d="M20 6c-7 0-12 5-12 12 0 8 4 13 5 19 .5 3 1 8 4 8 2.5 0 3-3 3.5-6 .5-3 1-7 5-7s4.5 4 5 7c.5 3 1 6 3.5 6 3 0 3.5-5 4-8 1-6 5-11 5-19 0-7-5-12-12-12-3 0-5 1-7 2-2-1-4-2-7-2Z"
      fill="#00B4E6"/>
    {/* inner ink swoosh */}
    <path d="M22 14c-3 2-5 5-5 9M28 12c-2 1-4 4-4 8" stroke="#0B1726" strokeWidth="2.5" strokeLinecap="round" fill="none"/>
    {/* implant screw */}
    <g stroke="#0B1726" fill="none" strokeWidth="2" strokeLinecap="round">
      <path d="M44 30v-3M44 34v-2M44 38v-2M44 42v-2"/>
    </g>
    <circle cx="44" cy="46" r="2.5" fill="#0B1726"/>
  </svg>
);

// ---------- Nav ----------
function Nav() {
  return (
    <nav className="nav" data-screen-label="Nav">
      <div className="nav-inner">
        <a className="brand" href="#top">
          <BrandMark />
          <div className="brand-text">
            <div className="name">Shifa Dental</div>
            <div className="sub">& Implant Centre</div>
          </div>
        </a>
        <div className="nav-links">
          <a href="#services">Services</a>
          <a href="#about">About</a>
          <a href="#testimonials">Reviews</a>
          <a href="#contact">Contact</a>
          <a href="dashboard.html">Staff login</a>
        </div>
        <div className="nav-cta">
          <div className="nav-phone">
            <Ico.Phone width="14" height="14" />
            <strong>+91 96361 69795</strong>
          </div>
          <a href="#book" className="btn btn-primary" style={{padding: "10px 16px", fontSize: 14}}>
            Book Visit
          </a>
        </div>
      </div>
    </nav>
  );
}

// ---------- Hero ----------
function Hero({ heroIllustration }) {
  return (
    <section className="hero" id="top" data-screen-label="Hero">
      <div className="container">
        <div className="hero-grid">
          <div>
            <span className="eyebrow"><span className="dot" />Now accepting new patients · Sikar</span>
            <h1 style={{marginTop: 18}}>
              A confident smile <br/>
              starts with <span className="accent">trusted care.</span>
            </h1>
            <p className="lead">
              Modern dentistry, gentle hands, and outcomes you can actually feel — from
              same-day implants to clear aligners, all under one roof in Sikar.
            </p>
            <div className="hero-cta">
              <a href="#book" className="btn btn-primary">
                Book an appointment <Ico.ArrowRight width="16" height="16" />
              </a>
              <a href="tel:+919636169795" className="btn btn-ghost">
                <Ico.Phone width="16" height="16" /> Call the clinic
              </a>
            </div>
            <div className="hero-trust">
              <div className="item">
                <div className="icon"><Ico.Shield width="20" height="20" /></div>
                <div className="label"><strong>10+ years</strong>of practice</div>
              </div>
              <div className="item">
                <div className="icon"><Ico.Tooth width="20" height="20" /></div>
                <div className="label"><strong>5,000+</strong>smiles restored</div>
              </div>
              <div className="item">
                <div className="icon"><Ico.Sparkle width="20" height="20" /></div>
                <div className="label"><strong>Sterile, modern</strong>operatory</div>
              </div>
            </div>
          </div>
          <HeroVisual variant={heroIllustration} />
        </div>
      </div>
    </section>
  );
}

function HeroVisual({ variant = "illustration" }) {
  return (
    <div className="hero-visual">
      {variant === "illustration" ? <HeroIllustration /> : <HeroIcon />}
      <div className="hero-badge tl">
        <div className="pill"><Ico.Calendar width="20" height="20" /></div>
        <div>
          <div className="lbl">Today's slots</div>
          <div className="val">5 available</div>
        </div>
      </div>
      <div className="hero-badge br">
        <div className="pill" style={{background: "#FFB400"}}>★</div>
        <div>
          <div className="lbl">Patient rating</div>
          <div className="val">4.9 / 5.0</div>
        </div>
      </div>
    </div>
  );
}

// SVG illustration: stylized tooth with sparkle, no real photos
function HeroIllustration() {
  return (
    <div className="photo" style={{
      background: "linear-gradient(160deg, #ffffff 0%, #d8eef5 100%)",
      display: "grid", placeItems: "center", overflow: "hidden", position: "relative"
    }}>
      <svg viewBox="0 0 400 400" width="86%" height="86%">
        <defs>
          <linearGradient id="toothG" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor="#ffffff"/>
            <stop offset="100%" stopColor="#cfeaf5"/>
          </linearGradient>
          <linearGradient id="cyanG" x1="0" y1="0" x2="1" y2="1">
            <stop offset="0%" stopColor="#00B4E6"/>
            <stop offset="100%" stopColor="#0098C6"/>
          </linearGradient>
        </defs>
        {/* soft ring */}
        <circle cx="200" cy="200" r="160" fill="none" stroke="#00B4E6" strokeOpacity=".15" strokeWidth="1.5" strokeDasharray="2 6"/>
        <circle cx="200" cy="200" r="125" fill="none" stroke="#00B4E6" strokeOpacity=".25" strokeWidth="1.2"/>
        {/* tooth body */}
        <path d="M140 90c-22 0-38 16-38 38 0 26 13 42 17 64 3 14 4 32 7 46 2 12 8 26 20 26 12 0 14-14 17-28 3-15 7-32 27-32s24 17 27 32c3 14 5 28 17 28 12 0 18-14 20-26 3-14 4-32 7-46 4-22 17-38 17-64 0-22-16-38-38-38-15 0-25 7-36 13-2 1-4 1-6 1s-4 0-6-1c-11-6-21-13-36-13Z"
          fill="url(#toothG)" stroke="#00B4E6" strokeWidth="6" strokeLinejoin="round"/>
        {/* shine */}
        <path d="M155 130c-12 8-20 22-20 38" stroke="#fff" strokeWidth="10" strokeLinecap="round" opacity=".9"/>
        <path d="M170 120c-7 4-12 11-14 18" stroke="#fff" strokeWidth="6" strokeLinecap="round" opacity=".7"/>
        {/* sparkles */}
        <g fill="url(#cyanG)">
          <path d="M310 110l4 12 12 4-12 4-4 12-4-12-12-4 12-4z" />
          <path d="M86 250l3 8 8 3-8 3-3 8-3-8-8-3 8-3z" />
          <path d="M328 280l2 6 6 2-6 2-2 6-2-6-6-2 6-2z" />
        </g>
      </svg>
    </div>
  );
}

function HeroIcon() {
  return (
    <div className="photo" style={{
      background: "linear-gradient(160deg, #00B4E6 0%, #0078A8 100%)",
      display: "grid", placeItems: "center", color: "white"
    }}>
      <BrandMark size={180} />
    </div>
  );
}

// ---------- Services ----------
const SERVICES = [
  { icon: "Implant", title: "Dental Implants", desc: "Permanent tooth replacement with titanium implants — chew, smile and speak with full confidence.", price: "Starting ₹18,000 / tooth" },
  { icon: "Root", title: "Root Canal Treatment", desc: "Painless, single-sitting RCT using rotary endodontics to save your natural tooth from extraction.", price: "Starting ₹3,500" },
  { icon: "Sparkle", title: "Teeth Whitening", desc: "Professional in-clinic whitening that brightens your smile by 4–6 shades in under an hour.", price: "Starting ₹6,000" },
  { icon: "Braces", title: "Orthodontic Treatment", desc: "Metal, ceramic and clear aligners — a straighter smile tailored to your lifestyle and budget.", price: "Starting ₹25,000" },
  { icon: "Kid", title: "Pediatric Dentistry", desc: "Gentle, fear-free dental care for kids — preventive checkups, sealants, and habit counseling.", price: "Starting ₹500 / visit" },
  { icon: "Shield", title: "Routine Check-up", desc: "Comprehensive oral exam, scaling and polishing — keep small issues from becoming big ones.", price: "Starting ₹800" },
];

function Services() {
  return (
    <section id="services" data-screen-label="Services">
      <div className="container">
        <div className="section-head">
          <span className="eyebrow"><span className="dot" />Our Services</span>
          <h2>Everything your smile needs,<br/>under one roof.</h2>
          <p>From routine cleaning to full-mouth rehabilitation, every treatment is delivered with modern equipment and a no-rush, patient-first approach.</p>
        </div>
        <div className="service-grid">
          {SERVICES.map((s) => {
            const I = Ico[s.icon];
            return (
              <div className="service-card" key={s.title}>
                <div className="ico"><I width="26" height="26" /></div>
                <h3>{s.title}</h3>
                <p>{s.desc}</p>
                <div className="price">
                  <strong>{s.price}</strong>
                  <Ico.ArrowRight width="16" height="16" />
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </section>
  );
}

// ---------- About / Doctor ----------
function About() {
  return (
    <section id="about" className="about-bg" data-screen-label="About">
      <div className="container">
        <div className="about-grid">
          <DoctorCard />
          <div>
            <span className="eyebrow"><span className="dot" />Meet your dentist</span>
            <h2 style={{marginTop: 14}}>A decade of careful, considered dentistry.</h2>
            <p className="lead" style={{marginTop: 14}}>
              Dr. Abid Ali Pathan founded Shifa Dental & Implant Centre with a simple
              promise — every patient leaves understanding their treatment, comfortable
              with the cost, and proud of their smile.
            </p>
            <div className="about-points">
              <div className="pt">
                <div className="num">1</div>
                <div>
                  <strong>Painless, modern protocols</strong>
                  <p>Single-sitting RCT, digital impressions, and ultrasonic scaling — no guesswork, no needless visits.</p>
                </div>
              </div>
              <div className="pt">
                <div className="num">2</div>
                <div>
                  <strong>Transparent pricing, always</strong>
                  <p>Written treatment plans before any work begins. No hidden fees, no surprise add-ons.</p>
                </div>
              </div>
              <div className="pt">
                <div className="num">3</div>
                <div>
                  <strong>Strict sterilisation standards</strong>
                  <p>Autoclaved instruments, disposable barriers, and fresh PPE for every patient — without exception.</p>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div className="stats-strip">
          <div className="stat"><div className="num">10+</div><div className="lbl">Years experience</div></div>
          <div className="stat"><div className="num">5,000+</div><div className="lbl">Happy patients</div></div>
          <div className="stat"><div className="num">800+</div><div className="lbl">Implants placed</div></div>
          <div className="stat"><div className="num">4.9★</div><div className="lbl">Avg. patient rating</div></div>
        </div>
      </div>
    </section>
  );
}

function DoctorCard() {
  return (
    <div className="doctor-card">
      <div className="reg">Reg. No. A-8404</div>
      <div className="silhouette">
        <img src="assets/abid.jpg" alt="Dr. Abid Ali Pathan" />
      </div>
      <div className="meta">
        <div className="deg">B.D.S., M.I.D.A.</div>
        <div className="name">Dr. Abid Ali Pathan</div>
        <p>Dental Surgeon & Implantologist · Member, Indian Dental Association. Trained in advanced implantology and aesthetic dentistry.</p>
      </div>
    </div>
  );
}

// ---------- Testimonials ----------
const TESTIMONIALS = [
  { name: "Pooja Sharma", area: "Piprali Road, Sikar", text: "I had been postponing my root canal for two years out of fear. Dr. Abid finished it in a single sitting, completely painless. The clinic is spotless and the staff are kind.", initials: "PS" },
  { name: "Rakesh Choudhary", area: "Bajaj Road, Sikar", text: "Got two implants placed last year — they feel exactly like my natural teeth. The pricing was transparent from day one and the follow-ups were thorough. Highly recommend.", initials: "RC" },
  { name: "Aisha Khan", area: "Subhash Chowk, Sikar", text: "Took my 7-year-old here and was so relieved. Dr. Abid was patient, explained every step to her, and she actually asks to go back. That tells you everything.", initials: "AK" },
];

function Testimonials() {
  return (
    <section id="testimonials" data-screen-label="Testimonials">
      <div className="container">
        <div className="section-head">
          <span className="eyebrow"><span className="dot" />What patients say</span>
          <h2>Real reviews from<br/>our Sikar community.</h2>
        </div>
        <div className="testi-grid">
          {TESTIMONIALS.map(t => (
            <div className="testi" key={t.name}>
              <div className="stars">★★★★★</div>
              <blockquote>"{t.text}"</blockquote>
              <div className="person">
                <div className="avatar">{t.initials}</div>
                <div>
                  <strong>{t.name}</strong>
                  <span>{t.area}</span>
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ---------- Booking form ----------
function Booking() {
  const [submitted, setSubmitted] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState("");
  const [apptId, setApptId] = useState(null);
  const [status, setStatus] = useState(null); // PENDING | CONFIRMED | CANCELLED
  const [slots, setSlots] = useState({});     // { [label]: { available, remaining } }
  const [loadingSlots, setLoadingSlots] = useState(false);
  const [form, setForm] = useState({
    name: "", phone: "", email: "", service: "", date: "", time: "", notes: "",
  });
  const onChange = (k) => (e) => setForm({ ...form, [k]: e.target.value });

  const reset = () => {
    setSubmitted(false); setError(""); setApptId(null); setStatus(null); setSlots({});
    setForm({ name:"", phone:"", email:"", service:"", date:"", time:"", notes:"" });
  };

  // Look up live availability for the chosen date.
  const loadAvailability = async (date) => {
    if (!API_BASE || !date) { setSlots({}); return; }
    setLoadingSlots(true);
    try {
      const res = await fetch(`${API_BASE}/availability?date=${encodeURIComponent(date)}`);
      const data = await res.json().catch(() => ({}));
      const map = {};
      (data.slots || []).forEach((s) => { map[s.time] = s; });
      setSlots(map);
    } catch (_) {
      setSlots({});
    } finally {
      setLoadingSlots(false);
    }
  };

  // When the date changes, refresh availability and clear a now-full selection.
  const onDateChange = (e) => {
    const date = e.target.value;
    setForm((f) => ({ ...f, date, time: "" }));
    loadAvailability(date);
  };

  const onSubmit = async (e) => {
    e.preventDefault();
    setError("");

    // Demo mode: no backend configured.
    if (!API_BASE) {
      setStatus("PENDING");
      setSubmitted(true);
      return;
    }

    setSubmitting(true);
    try {
      const res = await fetch(`${API_BASE}/appointments`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(form),
      });
      const data = await res.json().catch(() => ({}));
      if (res.status === 409) {
        // Slot filled up between loading and submitting — refresh and ask again.
        setError(data.error || "That slot just filled up. Please pick another time.");
        setForm((f) => ({ ...f, time: "" }));
        loadAvailability(form.date);
        return;
      }
      if (!res.ok) throw new Error(data.error || "Something went wrong. Please call the clinic.");
      setApptId(data.appointmentId);
      setStatus(data.status || "PENDING");
      setSubmitted(true);
    } catch (err) {
      setError(err.message || "Could not submit. Please call the clinic.");
    } finally {
      setSubmitting(false);
    }
  };

  // Poll appointment status every 10s until staff confirm or cancel it.
  useEffect(() => {
    if (!API_BASE || !apptId) return;
    if (status === "CONFIRMED" || status === "CANCELLED") return;
    const timer = setInterval(async () => {
      try {
        const res = await fetch(`${API_BASE}/appointments/${apptId}/status`);
        if (!res.ok) return;
        const data = await res.json();
        if (data.status) setStatus(data.status);
      } catch (_) { /* keep polling */ }
    }, 10000);
    return () => clearInterval(timer);
  }, [apptId, status]);

  return (
    <section id="book" className="book-bg" data-screen-label="Booking">
      <div className="container">
        <div className="book-grid">
          <div className="book-info">
            <span className="eyebrow"><span className="dot" />Book an appointment</span>
            <h2 style={{marginTop: 14}}>Pick a time. We'll confirm by call within an hour.</h2>
            <p className="lead">No long waits, no paperwork shuffle. Tell us what you need and we'll lock in a slot that works for you.</p>
            <div className="book-features">
              <div className="f">
                <div className="check"><Ico.Check width="14" height="14" /></div>
                <div>
                  <strong>Same-day appointments</strong>
                  <p>For toothache and emergencies — call us directly and we'll fit you in.</p>
                </div>
              </div>
              <div className="f">
                <div className="check"><Ico.Check width="14" height="14" /></div>
                <div>
                  <strong>Free first consultation</strong>
                  <p>Your first visit includes an oral exam and treatment plan — no charge, no obligation.</p>
                </div>
              </div>
              <div className="f">
                <div className="check"><Ico.Check width="14" height="14" /></div>
                <div>
                  <strong>EMI options available</strong>
                  <p>0% EMI on implants and orthodontic treatments through partner finance.</p>
                </div>
              </div>
            </div>
          </div>

          <div className="form-card">
            {submitted ? (
              <div className="form-success">
                {status === "CONFIRMED" ? (
                  <>
                    <div className="ok"><Ico.Check width="32" height="32" /></div>
                    <h3>Appointment confirmed 🎉</h3>
                    <p style={{marginTop: 6}}>Great news, {form.name || "see you soon"}!<br/>Your visit is confirmed{API_BASE ? " — we've sent a confirmation SMS to " + (form.phone || "your number") + (form.email ? " and " + form.email : "") + "." : "."}</p>
                  </>
                ) : status === "CANCELLED" ? (
                  <>
                    <div className="ok" style={{background:"#fde2e2", color:"#c0392b"}}>!</div>
                    <h3>Slot unavailable</h3>
                    <p style={{marginTop: 6}}>Sorry, that slot couldn't be confirmed. Please call us on +91 96361 69795 to pick another time.</p>
                  </>
                ) : (
                  <>
                    <div className="ok"><Ico.Clock width="32" height="32" /></div>
                    <h3>Request received</h3>
                    <p style={{marginTop: 6}}>Thanks {form.name || "for reaching out"}!<br/>Our team is reviewing your request{API_BASE ? " — this page updates automatically once it's confirmed." : " and will call you within an hour."}</p>
                    {API_BASE && <div className="form-sub" style={{marginTop: 10}}>Checking for confirmation…</div>}
                  </>
                )}
                <button onClick={reset} className="btn btn-ghost" style={{marginTop: 20}}>Book another</button>
              </div>
            ) : (
              <form onSubmit={onSubmit}>
                <h3>Request a visit</h3>
                <p className="form-sub">Fields marked * are required.</p>
                {error && <div className="form-error" style={{background:"#fde2e2", color:"#c0392b", padding:"10px 12px", borderRadius:10, marginBottom:12, fontSize:14}}>{error}</div>}
                <div className="row2">
                  <div className="field">
                    <label>Full name *</label>
                    <input required value={form.name} onChange={onChange("name")} placeholder="e.g. Pooja Sharma" />
                  </div>
                  <div className="field">
                    <label>Phone number *</label>
                    <input required type="tel" value={form.phone} onChange={onChange("phone")} placeholder="+91 ..." pattern="[0-9 +\-]{10,}"/>
                  </div>
                </div>
                <div className="field">
                  <label>Email (optional)</label>
                  <input type="email" value={form.email} onChange={onChange("email")} placeholder="you@example.com"/>
                </div>
                <div className="field">
                  <label>Service needed *</label>
                  <select required value={form.service} onChange={onChange("service")}>
                    <option value="">Choose a service</option>
                    {SERVICES.map(s => <option key={s.title} value={s.title}>{s.title}</option>)}
                    <option value="Other">Something else</option>
                  </select>
                </div>
                <div className="row2">
                  <div className="field">
                    <label>Preferred date *</label>
                    <input required type="date" value={form.date} min={new Date().toISOString().split("T")[0]} onChange={onDateChange} />
                  </div>
                  <div className="field">
                    <label>Preferred time *</label>
                    <select required value={form.time} onChange={onChange("time")} disabled={!!API_BASE && (!form.date || loadingSlots)}>
                      <option value="">
                        {API_BASE && !form.date ? "Pick a date first" : loadingSlots ? "Checking availability…" : "Pick a slot"}
                      </option>
                      {TIME_SLOTS.map((label) => {
                        const info = slots[label];
                        const full = !!API_BASE && info && !info.available;
                        const left = !!API_BASE && info && info.available ? ` — ${info.remaining} left` : "";
                        return (
                          <option key={label} value={label} disabled={full}>
                            {label}{full ? " — Full" : left}
                          </option>
                        );
                      })}
                    </select>
                  </div>
                </div>
                <div className="field">
                  <label>Anything we should know? (optional)</label>
                  <textarea value={form.notes} onChange={onChange("notes")} placeholder="Toothache since Monday, sensitive to cold..."/>
                </div>
                <button type="submit" className="btn btn-primary" disabled={submitting}>
                  {submitting ? "Sending…" : <>Request appointment <Ico.ArrowRight width="16" height="16" /></>}
                </button>
                <div className="form-foot">By submitting, you agree to be contacted by our clinic. We never share your details.</div>
              </form>
            )}
          </div>
        </div>
      </div>
    </section>
  );
}

// ---------- Contact ----------
function Contact() {
  return (
    <section id="contact" data-screen-label="Contact">
      <div className="container">
        <div className="section-head">
          <span className="eyebrow"><span className="dot" />Visit the clinic</span>
          <h2>We're easy to find,<br/>and easier to talk to.</h2>
        </div>
        <div className="contact-grid">
          <div>
            <div className="contact-list">
              <div className="ci">
                <div className="ico"><Ico.Pin width="20" height="20" /></div>
                <div>
                  <div className="lbl">Address</div>
                  <div className="val">Near IMax Hospital,<br/>Police Line Road, Sikar, Rajasthan</div>
                </div>
              </div>
              <div className="ci">
                <div className="ico"><Ico.Phone width="20" height="20" /></div>
                <div>
                  <div className="lbl">Phone</div>
                  <div className="val">+91 96361 69795</div>
                </div>
              </div>
              <div className="ci">
                <div className="ico"><Ico.Mail width="20" height="20" /></div>
                <div>
                  <div className="lbl">Email</div>
                  <div className="val">care@shifadental.in</div>
                </div>
              </div>
            </div>
            <div className="hours">
              <h4>Clinic hours</h4>
              <div className="row"><span>Mon – Sat</span><span>10:00 am – 8:00 pm</span></div>
              <div className="row"><span>Sunday</span><span>By appointment</span></div>
              <div className="row"><span>Emergency</span><span>Call any time</span></div>
            </div>
          </div>
          <ClinicMap />
        </div>
      </div>
    </section>
  );
}

// Real Google Map embed — keyless (no API key needed). To pin the exact spot,
// replace MAP_QUERY with precise coordinates, e.g. "27.6094,75.1399".
const MAP_QUERY = "Shifa Dental & Implant Centre, Police Line Road, Sikar, Rajasthan";

function ClinicMap() {
  const embedSrc = `https://maps.google.com/maps?q=${encodeURIComponent(MAP_QUERY)}&z=15&output=embed`;
  const directions = `https://www.google.com/maps/search/?api=1&query=${encodeURIComponent(MAP_QUERY)}`;
  return (
    <div className="map-card">
      <iframe
        title="Shifa Dental & Implant Centre location"
        src={embedSrc}
        loading="lazy"
        referrerPolicy="no-referrer-when-downgrade"
        allowFullScreen
        style={{ position: "absolute", inset: 0, width: "100%", height: "100%", border: 0 }}
      />
      <a
        href={directions}
        target="_blank"
        rel="noopener noreferrer"
        style={{
          position: "absolute", bottom: 14, left: 14, zIndex: 2,
          background: "#fff", color: "var(--c-ink)", padding: "9px 14px",
          borderRadius: 10, fontWeight: 600, fontSize: 13,
          boxShadow: "var(--shadow-pop)", display: "inline-flex", alignItems: "center", gap: 6,
        }}
      >
        <Ico.Pin width="14" height="14" /> Get directions
      </a>
    </div>
  );
}

// ---------- Footer ----------
function Footer() {
  return (
    <footer className="footer" data-screen-label="Footer">
      <div className="container">
        <div className="footer-grid">
          <div>
            <div className="brand" style={{marginBottom: 14}}>
              <BrandMark size={40} />
              <div className="brand-text">
                <div className="name" style={{color:"#fff"}}>Shifa Dental</div>
                <div className="sub">& Implant Centre</div>
              </div>
            </div>
            <p>Modern dentistry with a personal touch — proudly serving Sikar since 2015.</p>
          </div>
          <div>
            <h4>Services</h4>
            <ul>
              {SERVICES.slice(0,5).map(s => <li key={s.title}><a href="#services">{s.title}</a></li>)}
            </ul>
          </div>
          <div>
            <h4>Clinic</h4>
            <ul>
              <li><a href="#about">About Dr. Abid</a></li>
              <li><a href="#testimonials">Reviews</a></li>
              <li><a href="#book">Book Visit</a></li>
              <li><a href="#contact">Contact</a></li>
              <li><a href="dashboard.html">Staff login</a></li>
            </ul>
          </div>
          <div>
            <h4>Reach us</h4>
            <ul>
              <li><a href="tel:+919636169795">+91 96361 69795</a></li>
              <li><a href="mailto:care@shifadental.in">care@shifadental.in</a></li>
              <li>Police Line Road, Sikar</li>
              <li>Reg. No. A-8404</li>
            </ul>
          </div>
        </div>
        <div className="footer-bottom">
          <div>© 2026 Shifa Dental & Implant Centre. All rights reserved.</div>
          <div>Crafted with care · Sikar, Rajasthan</div>
        </div>
      </div>
    </footer>
  );
}

// ---------- WhatsApp FAB ----------
function WhatsApp() {
  const msg = encodeURIComponent("Hi Shifa Dental, I'd like to book an appointment.");
  return (
    <a className="wa-fab" href={`https://wa.me/919636169795?text=${msg}`} target="_blank" rel="noopener">
      <span className="ring"/>
      <Ico.WA width="22" height="22" />
      <span className="txt">Chat on WhatsApp</span>
    </a>
  );
}

// ---------- App ----------
function App() {
  return (
    <>
      <Nav />
      <Hero heroIllustration="illustration" />
      <Services />
      <About />
      <Testimonials />
      <Booking />
      <Contact />
      <Footer />
      <WhatsApp />
    </>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
