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

// ============================================================
// Router (hash-based, single-file SPA)
// ============================================================
const useHashRoute = () => {
  const get = () => {
    const h = window.location.hash.replace(/^#\/?/, "") || window.__BYTESGLUE_SHOWCASE_ROUTE || "";
    const [path, ...rest] = h.split("/");
    return { path: path || "home", sub: rest.join("/") };
  };
  const [route, setRoute] = useState(get());
  useEffect(() => {
    const onHash = () => {
      setRoute(get());
      window.scrollTo({ top: 0, behavior: "instant" });
    };
    window.addEventListener("hashchange", onHash);
    return () => window.removeEventListener("hashchange", onHash);
  }, []);
  return route;
};

const navigate = (path) => {
  window.location.hash = path.startsWith("#") ? path : `#/${path}`;
};

// ============================================================
// Top Nav — sticky, with treatment dropdown
// ============================================================
const NAV = [
  { label: "Treatments", path: "treatments", hasDropdown: true },
  { label: "About",      path: "about" },
  { label: "Reviews",    path: "reviews" },
  { label: "Pricing",    path: "pricing" },
  { label: "Contact",    path: "contact" },
];

const TopNav = ({ currentPath }) => {
  const [scrolled, setScrolled] = useState(false);
  const [open, setOpen] = useState(false);
  const [mobile, setMobile] = useState(false);

  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 24);
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  return (
    <>
      {/* Announcement bar */}
      <div className="anno-bar" style={{
        background: "var(--espresso)",
        color: "var(--ivory)",
        fontSize: 12,
        letterSpacing: "0.08em",
        padding: "9px 0",
        textAlign: "center",
      }}>
        <span className="live-dot" style={{ marginRight: 10, verticalAlign: "middle" }}></span>
        Free 15-minute consultation — book online, by phone or via WhatsApp · +971 58 195 5350
      </div>

      <header style={{
        position: "sticky",
        top: 0,
        zIndex: 90,
        background: scrolled ? "rgba(248, 244, 236, 0.92)" : "var(--ivory)",
        backdropFilter: scrolled ? "saturate(160%) blur(14px)" : "none",
        WebkitBackdropFilter: scrolled ? "saturate(160%) blur(14px)" : "none",
        borderBottom: scrolled ? "1px solid var(--line)" : "1px solid transparent",
        transition: "all 240ms ease",
      }}>
        <div className="container" style={{ display: "flex", alignItems: "center", justifyContent: "space-between", height: 80 }}>
          <a href="#/home" style={{ display: "flex", alignItems: "center", gap: 12 }}>
            <CCMonogram size={42} />
            <Wordmark height={13} />
          </a>

          <nav style={{ display: "flex", gap: 4, alignItems: "center" }} className="desktop-only">
            {NAV.map(item => (
              <div
                key={item.path}
                onMouseEnter={() => item.hasDropdown && setOpen(true)}
                onMouseLeave={() => item.hasDropdown && setOpen(false)}
                style={{ position: "relative" }}
              >
                <a
                  href={`#/${item.path}`}
                  style={{
                    padding: "10px 16px",
                    fontSize: 13,
                    letterSpacing: "0.08em",
                    fontWeight: 500,
                    color: currentPath === item.path ? "var(--gold-deep)" : "var(--espresso)",
                    display: "inline-flex",
                    alignItems: "center",
                    gap: 4,
                  }}
                >
                  {item.label}
                  {item.hasDropdown && <ChevronDown size={12}/>}
                </a>
                {item.hasDropdown && open && (
                  <div style={{
                    position: "absolute",
                    top: "100%",
                    left: 0,
                    minWidth: 340,
                    background: "var(--cream-card)",
                    border: "1px solid var(--line)",
                    borderRadius: 14,
                    padding: 10,
                    boxShadow: "var(--shadow-lift)",
                    display: "flex",
                    flexDirection: "column",
                  }}>
                    {window.TREATMENTS.map(t => (
                      <a key={t.slug} href={`#/treatments/${t.slug}`}
                        style={{
                          display: "flex",
                          justifyContent: "space-between",
                          alignItems: "center",
                          padding: "11px 14px",
                          borderRadius: 10,
                          gap: 16,
                          transition: "background 140ms",
                        }}
                        onMouseEnter={e => e.currentTarget.style.background = "rgba(201,162,75,0.1)"}
                        onMouseLeave={e => e.currentTarget.style.background = "transparent"}
                      >
                        <div>
                          <div style={{ fontFamily: "var(--f-display)", fontSize: 18, color: "var(--espresso)" }}>{t.title}</div>
                          <div style={{ fontSize: 11, color: "var(--espresso-soft)", letterSpacing: "0.04em" }}>{t.tag}</div>
                        </div>
                        <ChevronRight size={14}/>
                      </a>
                    ))}
                  </div>
                )}
              </div>
            ))}
          </nav>

          <div style={{ display: "flex", gap: 10, alignItems: "center" }} className="desktop-only">
            <a href="tel:+971581955350" className="btn btn--ghost btn--sm" aria-label="Call">
              <PhoneIcon /> +971 58 195 5350
            </a>
            <a href="#/book" className="btn btn--primary btn--sm">Book Consultation</a>
          </div>

          {/* Mobile toggle */}
          <button
            className="mobile-only"
            onClick={() => setMobile(!mobile)}
            aria-label="Menu"
            style={{
              background: "transparent",
              border: "1px solid var(--line-strong)",
              borderRadius: 8,
              padding: "10px 12px",
              cursor: "pointer",
            }}
          >
            <svg width="20" height="14" viewBox="0 0 20 14" fill="none" stroke="currentColor" strokeWidth="1.8">
              <path d="M0 1h20M0 7h20M0 13h20"/>
            </svg>
          </button>
        </div>

        {/* Mobile drawer */}
        {mobile && (
          <div className="mobile-only" style={{
            borderTop: "1px solid var(--line)",
            background: "var(--ivory)",
            padding: "16px 24px 24px",
          }}>
            {NAV.map(item => (
              <a key={item.path} href={`#/${item.path}`} onClick={() => setMobile(false)}
                style={{
                  display: "block",
                  padding: "12px 0",
                  borderBottom: "1px solid var(--line)",
                  fontSize: 16,
                  fontFamily: "var(--f-display)",
                  color: "var(--espresso)",
                }}>{item.label}</a>
            ))}
            <a href="#/book" onClick={() => setMobile(false)} className="btn btn--primary" style={{ marginTop: 18, width: "100%" }}>Book Consultation</a>
          </div>
        )}
      </header>
    </>
  );
};

// ============================================================
// WhatsApp Floating Action Button
// ============================================================
const WhatsAppFAB = () => {
  const [open, setOpen] = useState(false);
  return (
    <div style={{ position: "fixed", bottom: 24, right: 24, zIndex: 80, display: "flex", flexDirection: "column", alignItems: "flex-end", gap: 12 }}>
      {open && (
        <div className="card" style={{
          padding: "16px 18px",
          maxWidth: 280,
          fontSize: 14,
          color: "var(--espresso)",
          animation: "pageIn 220ms ease both",
        }}>
          <div style={{ fontFamily: "var(--f-display)", fontSize: 20, marginBottom: 4, color: "var(--espresso)" }}>
            Hi, can we help?
          </div>
          <div style={{ color: "var(--espresso-soft)", fontSize: 13, lineHeight: 1.5, marginBottom: 12 }}>
            Message us on WhatsApp. We typically reply within minutes during clinic hours.
          </div>
          <a className="btn btn--whatsapp btn--sm" style={{ width: "100%" }}
            href="https://wa.me/971581955350?text=Hi%20Covent%20Clinic%2C%20I%27d%20like%20to%20book%20a%20consultation"
            target="_blank" rel="noopener noreferrer">
            <WhatsAppIcon /> Start chat
          </a>
        </div>
      )}
      <button
        onClick={() => setOpen(!open)}
        aria-label="Open WhatsApp chat"
        style={{
          width: 60, height: 60,
          borderRadius: "50%",
          background: "#25D366",
          border: "none",
          boxShadow: "0 12px 28px -8px rgba(37, 211, 102, 0.5), 0 2px 6px rgba(0,0,0,0.15)",
          cursor: "pointer",
          display: "flex", alignItems: "center", justifyContent: "center",
          color: "white",
          transition: "transform 180ms ease",
        }}
        onMouseEnter={e => e.currentTarget.style.transform = "scale(1.06)"}
        onMouseLeave={e => e.currentTarget.style.transform = "scale(1)"}
      >
        <WhatsAppIcon size={28} />
      </button>
    </div>
  );
};

// ============================================================
// Fresha trust badge
// ============================================================
const FreshaBadge = ({ compact = false }) => (
  <a
    href="https://www.fresha.com/a/covent-clinic-dubai-westburry-business-tower-burj-khalifa-blvd-burj-khalifa-boulevard-gfhyh4ea"
    target="_blank" rel="noopener noreferrer"
    style={{
      display: "inline-flex",
      alignItems: "center",
      gap: 12,
      padding: compact ? "8px 14px" : "12px 18px",
      background: "var(--cream-card)",
      border: "1px solid var(--line)",
      borderRadius: 999,
      transition: "all 180ms",
    }}
    onMouseEnter={e => { e.currentTarget.style.borderColor = "var(--gold)"; e.currentTarget.style.transform = "translateY(-1px)"; }}
    onMouseLeave={e => { e.currentTarget.style.borderColor = "var(--line)"; e.currentTarget.style.transform = "translateY(0)"; }}
  >
    <Stars value={4.5} size={compact ? 13 : 15}/>
    <div style={{ display: "flex", flexDirection: "column", lineHeight: 1.1 }}>
      <strong style={{ fontSize: compact ? 13 : 15, color: "var(--charcoal)" }}>4.5 · 129 reviews</strong>
      <span style={{ fontSize: 10, letterSpacing: "0.12em", textTransform: "uppercase", color: "var(--espresso-soft)" }}>verified on Fresha</span>
    </div>
  </a>
);

// ============================================================
// Footer
// ============================================================
const Footer = () => (
  <footer style={{ background: "var(--espresso)", color: "rgba(248,244,236,0.85)", padding: "72px 0 36px", marginTop: 80 }}>
    <div className="container">
      <div style={{
        display: "grid",
        gridTemplateColumns: "1.4fr 1fr 1fr 1fr",
        gap: 56,
        paddingBottom: 56,
        borderBottom: "1px solid rgba(228, 206, 154, 0.18)",
      }} className="footer-grid">
        <div>
          <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 18 }}>
            <CCMonogram size={44} />
            <span style={{ fontFamily: "var(--f-script)", fontSize: 14, letterSpacing: "0.32em", color: "var(--gold-soft)" }}>COVENT CLINIC</span>
          </div>
          <p style={{ fontSize: 14, lineHeight: 1.65, maxWidth: 320, color: "rgba(248,244,236,0.7)" }}>
            Doctor-led aesthetic and cosmetic dermatology in Business Bay, Dubai. Natural results, medically delivered.
          </p>
          <div style={{ marginTop: 22 }}>
            <FreshaBadge compact />
          </div>
        </div>

        <div>
          <h4 className="eyebrow" style={{ color: "var(--gold-soft)", marginBottom: 16 }}>Treatments</h4>
          <ul style={{ listStyle: "none", padding: 0, margin: 0, display: "flex", flexDirection: "column", gap: 8 }}>
            {window.TREATMENTS.map(t => (
              <li key={t.slug}><a href={`#/treatments/${t.slug}`} style={{ fontSize: 14, color: "rgba(248,244,236,0.75)" }}>{t.title}</a></li>
            ))}
          </ul>
        </div>

        <div>
          <h4 className="eyebrow" style={{ color: "var(--gold-soft)", marginBottom: 16 }}>Clinic</h4>
          <ul style={{ listStyle: "none", padding: 0, margin: 0, display: "flex", flexDirection: "column", gap: 8 }}>
            <li><a href="#/about"   style={{ fontSize: 14, color: "rgba(248,244,236,0.75)" }}>About & Team</a></li>
            <li><a href="#/reviews" style={{ fontSize: 14, color: "rgba(248,244,236,0.75)" }}>Reviews</a></li>
            <li><a href="#/pricing" style={{ fontSize: 14, color: "rgba(248,244,236,0.75)" }}>Pricing</a></li>
            <li><a href="#/contact" style={{ fontSize: 14, color: "rgba(248,244,236,0.75)" }}>Visit</a></li>
            <li><a href="#/book"    style={{ fontSize: 14, color: "rgba(248,244,236,0.75)" }}>Book a Consultation</a></li>
          </ul>
        </div>

        <div>
          <h4 className="eyebrow" style={{ color: "var(--gold-soft)", marginBottom: 16 }}>Visit</h4>
          <p style={{ fontSize: 14, lineHeight: 1.65, margin: 0, color: "rgba(248,244,236,0.78)" }}>
            Westbury Tower 1, Office 307<br/>
            Business Bay, Dubai<br/>
            <span style={{ fontSize: 11, opacity: 0.6, fontStyle: "italic" }}>street name to confirm</span>
          </p>
          <div style={{ marginTop: 14, display: "flex", flexDirection: "column", gap: 6 }}>
            <a href="tel:+971581955350" style={{ fontSize: 14, color: "var(--gold-soft)" }}>+971 58 195 5350</a>
            <a href="https://wa.me/971581955350" target="_blank" rel="noopener" style={{ fontSize: 14, color: "rgba(248,244,236,0.78)" }}>WhatsApp</a>
            <a href="https://instagram.com/coventclinic" target="_blank" rel="noopener" style={{ fontSize: 14, color: "rgba(248,244,236,0.78)" }}>@coventclinic</a>
          </div>
        </div>
      </div>

      <div style={{
        display: "flex", justifyContent: "space-between", alignItems: "center",
        flexWrap: "wrap", gap: 16, paddingTop: 28,
        fontSize: 12, color: "rgba(248,244,236,0.55)",
      }}>
        <span>© 2026 Covent Clinic LLC · DHA-registered specialty clinic</span>
        <span style={{ fontSize: 11, maxWidth: 540, textAlign: "right" }}>
          All treatments are medical procedures. Results vary and a consultation is required before booking. Imagery for reference only.
        </span>
      </div>
    </div>
  </footer>
);

// ============================================================
// Hero image with graceful fallback to placeholder
// ============================================================
const HeroImage = ({ src, alt, label, style = {}, fit = "cover" }) => {
  const [errored, setErrored] = useState(false);
  if (errored || !src) {
    return (
      <div className="placeholder" style={{ aspectRatio: "4/5", ...style }}>
        {label || "image placeholder"}
      </div>
    );
  }
  return (
    <img
      src={src} alt={alt || ""}
      onError={() => setErrored(true)}
      style={{
        width: "100%", height: "100%", objectFit: fit,
        display: "block", borderRadius: "inherit",
        ...style,
      }}
    />
  );
};

Object.assign(window, {
  useHashRoute, navigate,
  TopNav, WhatsAppFAB, FreshaBadge, Footer, HeroImage,
});
