/* Shared components used across home + treatment pages */
const { useState: cUseState, useEffect: cUseEffect } = React;

/* HOME_PATH is set per-page in the HTML loader. For root index it's '#'. For treatment pages it's '../index.html#'. */
const HOME_PATH = window.HOME_PATH || '#';

/* Single source of truth for clinic hours. Status text is calculated in
   Asia/Kolkata so visitors abroad still see the clinic's actual local status. */
const CLINIC_TIME_ZONE = 'Asia/Kolkata';
const CLINIC_SCHEDULE = Object.freeze({
  weekday: Object.freeze({ open: 10 * 60, close: 20 * 60, label: '10:00 am - 8:00 pm' }),
  sunday: 'By appointment only',
});

function clinicClock(date = new Date()){
  const parts = new Intl.DateTimeFormat('en-GB', {
    timeZone: CLINIC_TIME_ZONE,
    weekday: 'short',
    hour: '2-digit',
    minute: '2-digit',
    hourCycle: 'h23',
  }).formatToParts(date);
  const value = (type) => parts.find((part) => part.type === type)?.value;
  return {
    weekday: value('weekday'),
    minutes: Number(value('hour')) * 60 + Number(value('minute')),
  };
}

function getClinicStatus(date = new Date()){
  const { weekday, minutes } = clinicClock(date);
  const { open, close } = CLINIC_SCHEDULE.weekday;

  if (weekday === 'Sun'){
    return {
      isOpen: false,
      tone: 'appointment',
      heroText: 'Sunday · By appointment',
      badge: 'By appointment',
      detail: 'Sunday · Call or WhatsApp us',
    };
  }

  if (minutes < open){
    return {
      isOpen: false,
      tone: 'closed',
      heroText: 'Opens today at 10:00 am',
      badge: 'Closed now',
      detail: 'Opens today · 10:00 am',
    };
  }

  if (minutes < close){
    return {
      isOpen: true,
      tone: 'open',
      heroText: 'Open now · Until 8:00 pm',
      badge: 'Open now',
      detail: 'Today · Until 8:00 pm',
    };
  }

  const isSaturday = weekday === 'Sat';
  return {
    isOpen: false,
    tone: 'closed',
    heroText: isSaturday ? 'Closed · Sunday by appointment' : 'Closed · Opens tomorrow at 10:00 am',
    badge: 'Closed now',
    detail: isSaturday ? 'Sunday · By appointment' : 'Opens tomorrow · 10:00 am',
  };
}

const NAV_LINKS = [
  { id: 'services', label: 'Treatments', home: true },
  { id: 'implants', label: 'Implants', home: true },
  { id: 'doctor', label: 'About', home: true },
  { id: 'gallery', label: 'Clinic', home: true },
  { id: 'reviews', label: 'Reviews', home: true },
  { id: 'contact', label: 'Contact', home: false },  // local on every page
];

function smoothScroll(id){
  const el = document.getElementById(id);
  if (!el) return;
  const y = el.getBoundingClientRect().top + window.scrollY - 70;
  window.scrollTo({ top: y, behavior: 'smooth' });
}

function navHref(link){
  if (link.id === 'contact') return '#contact';  // always local
  return link.home ? HOME_PATH + link.id : '#' + link.id;
}

function Nav({ active }){
  const [scrolled, setScrolled] = cUseState(false);
  cUseEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 12);
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  return (
    <header className={`nav ${scrolled ? 'scrolled' : ''}`}>
      <div className="container nav-inner">
        <a href={HOME_PATH === '#' ? '#home' : HOME_PATH.replace(/#$/, '')} className="brand">
          <span className="brand-mark"><Icon.Logo size={30} /></span>
          <span className="brand-text">
            <span className="b1">Puneet Dental Clinic</span>
            <span className="b2">& Implant Center</span>
          </span>
        </a>
        <nav className="nav-links">
          {NAV_LINKS.map(s => {
            const href = navHref(s);
            const onClick = (e) => {
              if (href.startsWith('#') && document.getElementById(s.id)){
                e.preventDefault();
                smoothScroll(s.id);
              }
            };
            return (
              <a key={s.id} href={href}
                className={`nav-link ${active === s.id ? 'active' : ''}`}
                onClick={onClick}
              >{s.label}</a>
            );
          })}
        </nav>
        <div className="nav-cta">
          <a className="btn btn-ghost" href="tel:+919930457845">
            <Icon.Phone size={16} /> Call
          </a>
          <a className="btn btn-primary" href="#contact" onClick={(e) => { if(document.getElementById('contact')){ e.preventDefault(); smoothScroll('contact'); } }}>
            Book appointment
          </a>
        </div>
      </div>
    </header>
  );
}

/* CONTACT FORM */
function ContactForm({ defaultTreatment }){
  const [submitted, setSubmitted] = cUseState(false);
  const [submitting, setSubmitting] = cUseState(false);
  const [submitError, setSubmitError] = cUseState('');
  const [form, setForm] = cUseState({ name: '', phone: '', treatment: defaultTreatment || '', date: '', message: '', consent: false, website: '' });
  const [errors, setErrors] = cUseState({});

  function onChange(k, v){ setForm({ ...form, [k]: v }); if(errors[k]) setErrors({ ...errors, [k]: null }); }

  async function submit(e){
    e.preventDefault();
    const er = {};
    if (!form.name.trim()) er.name = 'Please enter your name';
    if (!form.phone.trim() || !/^[\d\s+()-]{8,}$/.test(form.phone)) er.phone = 'Please enter a valid phone number';
    if (!form.consent) er.consent = 'Please confirm that the clinic may contact you';
    if (Object.keys(er).length){ setErrors(er); return; }

    setSubmitting(true);
    setSubmitError('');
    try {
      const response = await fetch('https://formspree.io/f/xnjejrqq', {
        method: 'POST',
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          _subject: `Appointment request — ${form.name}`,
          name: form.name,
          phone: form.phone,
          preferredDate: form.date || 'Not specified',
          treatment: form.treatment || 'Not specified',
          message: form.message || 'No message',
          consent: form.consent ? 'Confirmed' : 'Not confirmed',
          _gotcha: form.website,
        }),
      });
      if (!response.ok) throw new Error('Request failed');
      setSubmitted(true);
    } catch (error) {
      setSubmitError('We could not send your request just now. Please WhatsApp or call the clinic instead.');
    } finally {
      setSubmitting(false);
    }
  }

  if (submitted){
    return (
      <div className="contact-form">
        <div className="form-success">
          <div className="ic"><Icon.Check size={28} /></div>
          <h3>Thank you, {form.name.split(' ')[0]}.</h3>
          <p>Your appointment request has been sent directly to the clinic. We'll call you back to confirm a suitable time.</p>
          <a className="btn btn-whats" style={{ marginBottom: 10 }} href="https://wa.me/919930457845?text=Hello%2C%20I%27d%20like%20to%20book%20an%20appointment%20at%20Puneet%20Dental%20Clinic.">
            <Icon.Whatsapp size={16} /> WhatsApp the clinic
          </a>
          <button className="btn btn-ghost" onClick={() => { setSubmitted(false); setForm({ name: '', phone: '', treatment: '', date: '', message: '', consent: false, website: '' }); }}>
            Book another appointment
          </button>
        </div>
      </div>
    );
  }

  return (
    <form className="contact-form" onSubmit={submit} noValidate>
      <h3>Request an appointment</h3>
      <p className="sub">Fill in your details and we'll call you back to confirm a time that works for you.</p>
      <div className="field">
        <label>Your name</label>
        <input type="text" value={form.name} onChange={(e) => onChange('name', e.target.value)} placeholder="Full name" />
        {errors.name && <span className="err">{errors.name}</span>}
      </div>
      <div className="field-row">
        <div className="field">
          <label>Phone number</label>
          <input type="tel" value={form.phone} onChange={(e) => onChange('phone', e.target.value)} placeholder="+91 9X XXX XXXXX" />
          {errors.phone && <span className="err">{errors.phone}</span>}
        </div>
        <div className="field">
          <label>Preferred date</label>
          <input type="date" value={form.date} onChange={(e) => onChange('date', e.target.value)} />
        </div>
      </div>
      <div className="field">
        <label>Treatment needed</label>
        <select value={form.treatment} onChange={(e) => onChange('treatment', e.target.value)}>
          <option value="">Select a treatment (optional)</option>
          {Object.values(window.TREATMENTS || {}).map(t => (
            <option key={t.h1}>{t.h1}</option>
          ))}
        </select>
      </div>
      <div className="field">
        <label>Message (optional)</label>
        <textarea value={form.message} onChange={(e) => onChange('message', e.target.value)} placeholder="Tell us briefly what's bothering you, or any concerns you'd like to mention." />
      </div>
      <div className="hp-field" aria-hidden="true">
        <label>Website<input type="text" tabIndex="-1" autoComplete="off" value={form.website} onChange={(e) => onChange('website', e.target.value)} /></label>
      </div>
      <label className="consent-row">
        <input type="checkbox" checked={form.consent} onChange={(e) => onChange('consent', e.target.checked)} />
        <span>I consent to Puneet Dental Clinic using these details to contact me about this appointment request.<small>Used only to respond to this request. Please do not include sensitive medical information.</small></span>
      </label>
      {errors.consent && <span className="consent-error">{errors.consent}</span>}
      <p className="callback"><Icon.Phone size={14} /> We'll call you back to confirm your appointment.</p>
      {submitError && <p className="submit-error" role="alert">{submitError}</p>}
      <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap' }}>
        <button type="submit" className="btn btn-primary btn-lg" style={{ flex: 1, justifyContent: 'center' }} disabled={submitting}>
          {submitting ? 'Sending request…' : 'Request appointment'} {!submitting && <Icon.Arrow size={14} />}
        </button>
        <a href="https://wa.me/919930457845?text=Hello%2C%20I%27d%20like%20to%20book%20an%20appointment%20at%20Puneet%20Dental%20Clinic." className="btn btn-whats btn-lg">
          <Icon.Whatsapp size={16} />
        </a>
      </div>
    </form>
  );
}

/* CONTACT SECTION */
function Contact({ defaultTreatment }){
  return (
    <section id="contact" className="contact">
      <div className="container">
        <div className="section-head">
          <span className="eyebrow">Visit us</span>
          <h2>Come in, or <em>we'll come to you.</em></h2>
          <p>Easy to find. Easier to reach. Andheri West, near MHADA 4 Bungalows — with parking and a pleasant waiting space.</p>
        </div>
        <div className="contact-grid">
          <ContactForm defaultTreatment={defaultTreatment} />
          <div className="contact-info">
            <div className="info-card">
              <div className="ic"><Icon.Pin size={20} /></div>
              <div>
                <h4>Clinic address</h4>
                <div className="val">Shop No 12, Sandeep Sarovar CHS, SVP Nagar,<br/>MHADA 4 Bungalows, Near Telephone Exchange,<br/>Andheri West, Mumbai — 400 053</div>
                <a href="https://www.google.com/maps/search/?api=1&query=Puneet+Dental+Clinic+%26+Implant+Centre+Shop+No+12+Sandeep+Sarovar+CHS+SVP+Nagar+MHADA+4+Bungalows+Andheri+West+Mumbai+400053" target="_blank" rel="noopener" style={{ fontSize: 13, fontFamily: 'DM Sans, sans-serif', marginTop: 6, display: 'inline-flex', alignItems: 'center', gap: 4 }}>
                  Get directions <Icon.Arrow size={11} />
                </a>
              </div>
            </div>
            <div className="info-card">
              <div className="ic"><Icon.Phone size={20} /></div>
              <div>
                <h4>Call or WhatsApp</h4>
                <div className="val"><a href="tel:+919930457845">+91 9930457845</a></div>
                <a href="https://wa.me/919930457845?text=Hello%2C%20I%27d%20like%20to%20book%20an%20appointment%20at%20Puneet%20Dental%20Clinic." style={{ fontSize: 13, fontFamily: 'DM Sans, sans-serif', marginTop: 6, display: 'inline-flex', alignItems: 'center', gap: 4, color: '#1FAD58' }}>
                  Open WhatsApp <Icon.Arrow size={11} />
                </a>
              </div>
            </div>
            <div className="info-card">
              <div className="ic"><Icon.Clock size={20} /></div>
              <div>
                <h4>Clinic hours</h4>
                <div className="val" style={{ fontSize: 14.5 }}>
                  Mon - Sat &nbsp; {CLINIC_SCHEDULE.weekday.label}<br/>
                  Sunday &nbsp;&nbsp;&nbsp; {CLINIC_SCHEDULE.sunday}
                </div>
              </div>
            </div>
            <div className="map-card">
              <iframe title="Puneet Dental Clinic & Implant Centre on Google Maps" src="https://maps.google.com/maps?q=Puneet%20Dental%20Clinic%20%26%20Implant%20Centre%2C%20Sandeep%20Sarovar%20CHS%2C%20SVP%20Nagar%2C%20MHADA%204%20Bungalows%2C%20Andheri%20West%2C%20Mumbai%20400053&z=16&output=embed" style={{ width: '100%', height: '100%', minHeight: 280, border: 0, display: 'block' }} loading="lazy" allowFullScreen></iframe>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

/* FOOTER */
function Footer(){
  return (
    <footer className="footer">
      <div className="container">
        <div className="footer-grid">
          <div className="footer-brand">
            <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 10 }}>
              <span style={{ width: 42, height: 42, borderRadius: 10, background: '#fff', display: 'grid', placeItems: 'center' }}>
                <Icon.Logo size={28} />
              </span>
              <div>
                <div className="b1">Puneet Dental Clinic</div>
                <div className="b2">& Implant Center</div>
              </div>
            </div>
            <p>Gentle family dentistry and advanced implant care in Andheri West, Mumbai. Trusted since 2001.</p>
          </div>
          <div>
            <h5>Treatments</h5>
            <div className="footer-list">
              <a href={HOME_PATH === '#' ? '#implants' : HOME_PATH + 'implants'}>Dental implants</a>
              <a href={HOME_PATH === '#' ? '#services' : HOME_PATH + 'services'}>Root canal</a>
              <a href={HOME_PATH === '#' ? '#services' : HOME_PATH + 'services'}>Crowns & bridges</a>
              <a href={HOME_PATH === '#' ? '#services' : HOME_PATH + 'services'}>Teeth whitening</a>
              <a href={HOME_PATH === '#' ? '#services' : HOME_PATH + 'services'}>Pediatric care</a>
            </div>
          </div>
          <div>
            <h5>Clinic</h5>
            <div className="footer-list">
              <a href={HOME_PATH === '#' ? '#doctor' : HOME_PATH + 'doctor'}>About Dr. Puneet</a>
              <a href={HOME_PATH === '#' ? '#gallery' : HOME_PATH + 'gallery'}>Clinic photos</a>
              <a href={HOME_PATH === '#' ? '#reviews' : HOME_PATH + 'reviews'}>Patient reviews</a>
              <a href={HOME_PATH === '#' ? '#faq' : HOME_PATH + 'faq'}>FAQs</a>
              <a href="#contact">Contact</a>
            </div>
          </div>
          <div>
            <h5>Reach us</h5>
            <div className="footer-list">
              <a href="tel:+919930457845">+91 99304 57845</a>
              <a href="https://wa.me/919930457845?text=Hello%2C%20I%27d%20like%20to%20book%20an%20appointment%20at%20Puneet%20Dental%20Clinic.">WhatsApp the clinic</a>
              <a href="https://www.google.com/maps/search/?api=1&query=Puneet+Dental+Clinic+%26+Implant+Centre+Shop+No+12+Sandeep+Sarovar+CHS+SVP+Nagar+MHADA+4+Bungalows+Andheri+West+Mumbai+400053">MHADA 4 Bungalows,<br/>Andheri West, Mumbai</a>
              <span style={{ color: 'rgba(255,255,255,.6)', fontSize: 14, fontFamily: 'DM Sans, sans-serif' }}>Mon-Sat · 10am-8pm</span>
            </div>
          </div>
        </div>
        <div className="footer-bottom">
          <div>© 2026 Puneet Dental Clinic & Implant Center. All rights reserved.</div>
          <div>Reg. Maharashtra State Dental Council · Mumbai</div>
        </div>
      </div>
    </footer>
  );
}

/* MOBILE BAR */
function MobileBar(){
  return (
    <div className="mobile-bar">
      <div className="mobile-bar-grid">
        <a href="tel:+919930457845" className="mb"><Icon.Phone size={20} /> Call</a>
        <a href="https://wa.me/919930457845?text=Hello%2C%20I%27d%20like%20to%20book%20an%20appointment%20at%20Puneet%20Dental%20Clinic." className="mb mb-whats"><Icon.Whatsapp size={20} /> WhatsApp</a>
        <a href="https://www.google.com/maps/search/?api=1&query=Puneet+Dental+Clinic+%26+Implant+Centre+Shop+No+12+Sandeep+Sarovar+CHS+SVP+Nagar+MHADA+4+Bungalows+Andheri+West+Mumbai+400053" className="mb"><Icon.Pin size={20} /> Directions</a>
        <button className="mb mb-book" onClick={() => smoothScroll('contact')}><Icon.Calendar size={20} /> Book</button>
      </div>
    </div>
  );
}

/* LIGHTBOX */
function Lightbox({ src, onClose }){
  cUseEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [onClose]);
  if (!src) return null;
  return (
    <div className="lightbox" onClick={onClose}>
      <button className="lightbox-close" onClick={onClose}><Icon.Close size={20} /></button>
      <img src={src} alt="" onClick={(e) => e.stopPropagation()} />
    </div>
  );
}

Object.assign(window, { Nav, Footer, MobileBar, Lightbox, Contact, ContactForm, smoothScroll, HOME_PATH, CLINIC_SCHEDULE, getClinicStatus });
