// ─────────── Booking (multi-step) ───────────
const BOOK_TREATMENTS = [
  { id: 'consult',    name: 'Free Consult', desc: 'Just exploring' },
  { id: 'invisalign', name: 'Invisalign',   desc: 'Clear aligners' },
  { id: 'braces',     name: 'Braces',       desc: 'Orthodontics' },
  { id: 'implants',   name: 'Implants',     desc: 'Single or full-arch' },
  { id: 'cosmetic',   name: 'Crowns / Veneers', desc: 'Smile design' },
  { id: 'rct',        name: 'Root Canal',   desc: 'Painless RCT' },
  { id: 'whitening',  name: 'Whitening',    desc: 'Laser session' },
  { id: 'kids',       name: 'Paediatric',   desc: 'For my child' },
];

const BOOK_BRANCHES = [
  { id: 'east', name: 'Mulund East', desc: 'Neelam Nagar' },
  { id: 'west', name: 'Mulund West', desc: 'The Gateway' },
];

const BOOK_TIMES = ['10:00', '11:00', '12:00', '14:00', '15:30', '17:00', '18:00', '19:00'];

const dateLabels = () => {
  const out = [];
  const days = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
  const today = new Date();
  for (let i = 0; i < 6; i++) {
    const d = new Date(today);
    d.setDate(today.getDate() + i);
    out.push({
      id: d.toISOString().slice(0,10),
      day: i === 0 ? 'Today' : i === 1 ? 'Tomorrow' : days[d.getDay()],
      date: d.getDate(),
      month: d.toLocaleString('en', { month: 'short' }),
    });
  }
  return out;
};

const BookingSection = () => {
  const [step, setStep] = React.useState(0);
  const [data, setData] = React.useState({
    treatment: '',
    branch: '',
    date: '',
    time: '',
    name: '',
    phone: '',
    email: '',
    note: '',
  });

  const dates = React.useMemo(() => dateLabels(), []);
  const set = (k, v) => setData(d => ({ ...d, [k]: v }));

  const canNext = () => {
    if (step === 0) return !!data.treatment;
    if (step === 1) return !!data.branch;
    if (step === 2) return !!data.date && !!data.time;
    if (step === 3) return data.name.length > 1 && data.phone.length > 6;
    return false;
  };

  const confirmBooking = () => {
    const treatmentName = BOOK_TREATMENTS.find(t => t.id === data.treatment)?.name || data.treatment;
    const branchName = BOOK_BRANCHES.find(b => b.id === data.branch)?.name || data.branch;
    const lines = [
      '🦷 *New Appointment Request — Align-O-Dent*',
      '',
      `*Name:* ${data.name}`,
      `*Phone:* ${data.phone}`,
      data.email ? `*Email:* ${data.email}` : null,
      `*Treatment:* ${treatmentName}`,
      `*Branch:* ${branchName}`,
      `*When:* ${data.date}, ${data.time}`,
      data.note ? `*Note:* ${data.note}` : null,
    ].filter(Boolean).join('\n');

    const url = `https://wa.me/919321859061?text=${encodeURIComponent(lines)}`;
    window.open(url, '_blank', 'noopener,noreferrer');
    setStep(4);
  };

  const steps = ['Treatment', 'Branch', 'Time', 'You', 'Done'];

  return (
    <section id="book" className="book">
      <div className="wrap">
        <p className="eyebrow reveal"><span className="dot"></span>Book an appointment</p>
        <h2 className="reveal reveal-delay-1">Tell us what you need.<br/><em>We'll handle the rest.</em></h2>

        <div className="book-card reveal reveal-delay-2">
          <div className="book-steps">
            {steps.map((s, i) => (
              <div key={s} className={`book-step ${i === step ? 'active' : ''} ${i < step ? 'done' : ''}`}>
                <span className="n">{i < step ? <Icon name="check" size={12}/> : i + 1}</span>
                <span className="lbl">{s}</span>
              </div>
            ))}
          </div>

          {step === 0 && (
            <div className="book-panel">
              <div className="book-options">
                {BOOK_TREATMENTS.map(t => (
                  <button
                    key={t.id}
                    className={`book-opt ${data.treatment === t.id ? 'active' : ''}`}
                    onClick={() => set('treatment', t.id)}
                  >
                    <span className="name">{t.name}</span>
                    <span className="desc">{t.desc}</span>
                  </button>
                ))}
              </div>
              <a
                href="https://wa.me/919321859061?text=Hi%2C%20I%27d%20like%20to%20schedule%20an%20appointment%20at%20Align-O-Dent."
                target="_blank"
                rel="noopener noreferrer"
                className="book-doodle-link"
              >
                <span className="ico"><Icon name="calendar" size={16}/></span>
                <span className="txt">Prefer to pick a slot yourself? <b>Schedule a meeting with me</b></span>
                <span className="arr"><Icon name="arrow" size={14}/></span>
              </a>
            </div>
          )}

          {step === 1 && (
            <div className="book-panel">
              <div className="book-options">
                {BOOK_BRANCHES.map(b => (
                  <button
                    key={b.id}
                    className={`book-opt ${data.branch === b.id ? 'active' : ''}`}
                    onClick={() => set('branch', b.id)}
                  >
                    <span className="name">{b.name}</span>
                    <span className="desc">{b.desc}</span>
                  </button>
                ))}
              </div>
            </div>
          )}

          {step === 2 && (
            <div className="book-panel">
              <div className="book-options" style={{gridTemplateColumns:'repeat(auto-fit, minmax(110px, 1fr))'}}>
                {dates.map(d => (
                  <button
                    key={d.id}
                    className={`book-opt ${data.date === d.id ? 'active' : ''}`}
                    onClick={() => set('date', d.id)}
                    style={{padding:'18px', textAlign:'center', alignItems:'center'}}
                  >
                    <span className="desc">{d.day}</span>
                    <span className="name" style={{fontSize:32}}>{d.date}</span>
                    <span className="desc">{d.month}</span>
                  </button>
                ))}
              </div>
              <div style={{marginTop: 20}}>
                <div className="eyebrow" style={{color:'rgba(250,246,240,.5)', marginBottom: 12}}>Available slots</div>
                <div className="book-times">
                  {BOOK_TIMES.map((t, i) => (
                    <button
                      key={t}
                      disabled={i === 2}
                      className={`book-time ${data.time === t ? 'active' : ''}`}
                      onClick={() => set('time', t)}
                    >{t}</button>
                  ))}
                </div>
              </div>
            </div>
          )}

          {step === 3 && (
            <div className="book-panel">
              <input className="book-input" placeholder="Your full name" value={data.name} onChange={e => set('name', e.target.value)} />
              <div className="book-row">
                <input className="book-input" placeholder="Phone number" value={data.phone} onChange={e => set('phone', e.target.value)} />
                <input className="book-input" placeholder="Email (optional)" value={data.email} onChange={e => set('email', e.target.value)} />
              </div>
              <textarea className="book-input" placeholder="Anything we should know? Existing pain, dental history, anxieties..." rows="3" value={data.note} onChange={e => set('note', e.target.value)} style={{resize:'vertical', fontFamily:'var(--sans)'}}></textarea>
            </div>
          )}

          {step === 4 && (
            <div className="book-success">
              <div className="check"><Icon name="check" size={28}/></div>
              <h3>You're booked in.</h3>
              <p>Your request has been sent to the clinic via WhatsApp. The team will confirm your slot on <b style={{color:'var(--gold-soft)'}}>{data.phone}</b> shortly.</p>
              <div className="book-summary" style={{maxWidth: 500, margin: '0 auto'}}>
                <div className="row"><span className="k">Treatment</span><span className="v">{BOOK_TREATMENTS.find(t => t.id === data.treatment)?.name}</span></div>
                <div className="row"><span className="k">Branch</span><span className="v">{BOOK_BRANCHES.find(t => t.id === data.branch)?.name}</span></div>
                <div className="row"><span className="k">When</span><span className="v">{data.date} · {data.time}</span></div>
                <div className="row"><span className="k">Patient</span><span className="v">{data.name}</span></div>
              </div>
              <button className="book-next" onClick={() => { setStep(0); setData({ treatment:'', branch:'', date:'', time:'', name:'', phone:'', email:'', note:'' }); }}>
                <span>Book another</span>
                <Icon name="arrow" size={14}/>
              </button>
            </div>
          )}

          {step < 4 && (
            <>
              {step === 3 && (
                <div className="book-summary">
                  <div className="row"><span className="k">Treatment</span><span className="v">{BOOK_TREATMENTS.find(t => t.id === data.treatment)?.name}</span></div>
                  <div className="row"><span className="k">Branch</span><span className="v">{BOOK_BRANCHES.find(t => t.id === data.branch)?.name}</span></div>
                  <div className="row"><span className="k">When</span><span className="v">{data.date}, {data.time}</span></div>
                </div>
              )}
              <div className="book-nav">
                <button className="book-back" onClick={() => setStep(Math.max(0, step - 1))} disabled={step === 0}>← Back</button>
                <button className="book-next" disabled={!canNext()} onClick={() => step === 3 ? confirmBooking() : setStep(step + 1)}>
                  <span>{step === 3 ? 'Confirm booking' : 'Continue'}</span>
                  <Icon name="arrow" size={14}/>
                </button>
              </div>
            </>
          )}
        </div>

        <div style={{marginTop: 28, display:'flex', gap: 28, flexWrap:'wrap', color:'rgba(250,246,240,0.5)', fontFamily:'var(--mono)', fontSize: 11, letterSpacing:'.16em', textTransform:'uppercase'}}>
          <span style={{display:'flex',alignItems:'center',gap:8}}><Icon name="whatsapp" size={14}/> WhatsApp confirmation</span>
          <span style={{display:'flex',alignItems:'center',gap:8}}><Icon name="shield" size={14}/> No card needed</span>
          <span style={{display:'flex',alignItems:'center',gap:8}}><Icon name="calendar" size={14}/> Reschedule free up to 4h before</span>
        </div>
      </div>
    </section>
  );
};

// ─────────── FAQ ───────────
const FAQS = [
  { q: 'Is the first consultation really free?', a: 'Yes. The first sit-down, including X-ray review if you bring one, is on us. We use it to listen, examine, and tell you whether you actually need treatment. No pressure, no card on file.' },
  { q: 'How long do Invisalign or braces take?', a: 'Most cases finish between 8 and 24 months depending on complexity. We give you a written timeline on day one and re-confirm it after each adjustment.' },
  { q: 'Do you handle dental emergencies?', a: 'Yes, call +91 93218 59061 directly. We keep buffer slots every day for emergencies and try to see you within 24 hours.' },
  { q: 'Is the root canal really painless?', a: 'Numbing is given proper time to take full effect, then we use rotary instruments and apex locators. Most patients say the procedure is more comfortable than the toothache that brought them in.' },
  { q: 'Do you accept insurance?', a: 'We work with cashless billing for major Indian and corporate insurers. Let us know your provider when you book and we\'ll confirm coverage.' },
  { q: 'Are children seen at both branches?', a: 'Yes. We use behavioural-management techniques with younger children. No straps, no fear-words. Parents stay in the room.' },
];

const FAQSection = () => {
  const [open, setOpen] = React.useState(0);
  return (
    <section className="faq-v2">
      <div className="wrap">
        <div className="faq-v2-head reveal">
          <p className="eyebrow"><span className="dot"></span>FAQs</p>
          <h2>Patient <span>Questions.</span></h2>
        </div>
        <div className="faq-v2-list reveal reveal-delay-1">
          {FAQS.map((f, i) => (
            <div key={i} className={`faq-v2-item ${open === i ? 'open' : ''}`}>
              <button className="faq-v2-q" onClick={() => setOpen(open === i ? -1 : i)}>
                <span className="q">{f.q}</span>
                <span className="ico"><Icon name={open === i ? 'minus' : 'plus'} size={16}/></span>
              </button>
              <div className="faq-v2-a"><p>{f.a}</p></div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
};

// ─────────── Footer ───────────
const Footer = () => (
  <footer className="footer">
    <div className="wrap">
      <div className="footer-grid">
        <div className="footer-col footer-col-brand">
          <div style={{marginBottom: 24}}>
            <img src="assets/logo.png" alt="Align-O-Dent" className="brand-logo brand-logo-lg" />
          </div>
          <p className="footer-blurb">Unleashing <em>smiles</em>,<br/>one tooth at a time. Since 2018.</p>
          <p className="footer-desc">Mulund's only multispeciality dental clinic run by a husband-wife specialist duo — an orthodontist and a prosthodontist. Invisalign, braces, implants, crowns and painless root canals, all under one roof.</p>
          <div className="footer-socials">
            <a href="https://www.instagram.com/alignodentt/" target="_blank" rel="noopener noreferrer" aria-label="Instagram" className="footer-icon-btn">
              <Icon name="instagram" size={20}/>
            </a>
            <a href="https://www.facebook.com/alignodent/" target="_blank" rel="noopener noreferrer" aria-label="Facebook" className="footer-icon-btn">
              <Icon name="facebook" size={20}/>
            </a>
            <a href="https://wa.me/919321859061" target="_blank" rel="noopener noreferrer" aria-label="WhatsApp" className="footer-icon-btn footer-icon-wa">
              <Icon name="whatsapp" size={20}/>
            </a>
          </div>
        </div>

        <div className="footer-col">
          <h4>Treatments</h4>
          <ul>
            <li><a href="/treatments">Invisalign</a></li>
            <li><a href="/treatments">Braces</a></li>
            <li><a href="/treatments">Implants</a></li>
            <li><a href="/treatments">Crowns &amp; Veneers</a></li>
            <li><a href="/treatments">Root Canal</a></li>
            <li><a href="/treatments">Whitening</a></li>
          </ul>
        </div>

        <div className="footer-col">
          <h4>Branch 01 · East</h4>
          <ul>
            <li>Shop No. 2, 9/C</li>
            <li>Neelam Nagar, Gavanpada</li>
            <li>Mulund East, Mumbai 400081</li>
          </ul>
          <h4 style={{marginTop: 28}}>Branch 02 · West</h4>
          <ul>
            <li>Unit 307, The Gateway by Wadhwa</li>
            <li>Hira Nagar GMLR, Mulund West</li>
            <li>Mumbai 400081</li>
          </ul>
        </div>

        <div className="footer-col">
          <h4>Reach us</h4>
          <ul>
            <li><a href="tel:+919321859061">+91 93218 59061</a></li>
            <li><a href="mailto:abhijit@alignodent.com">abhijit@alignodent.com</a></li>
            <li>WhatsApp · 10am – 8pm</li>
          </ul>
          <h4 style={{marginTop: 28}}>Hours</h4>
          <ul>
            <li>East · Mon–Sat · 10:00 – 20:00</li>
            <li>West · Mon–Sun · 10:00 – 20:00</li>
            <li>Emergency · 24/7 on call</li>
          </ul>
        </div>
      </div>

      <div className="footer-marquee">Smile <em>&amp;</em> Shine · Smile <em>&amp;</em> Shine</div>

      <div className="footer-bottom">
        <span>© 2018–{new Date().getFullYear()} Dr. Shanbhag&apos;s Align‑O‑Dent · All rights reserved</span>
        <span className="footer-credit">
          Developed &amp; Powered by <a href="https://acquirenow.net" target="_blank" rel="noopener noreferrer">Acquire Now</a>
        </span>
      </div>
    </div>
  </footer>
);

Object.assign(window, { BookingSection, FAQSection, Footer });
