/* ==========================================================
   Harvard House Montessori — Premium Digital Business Card
   React + Tailwind + Lucide
   ========================================================== */

const { useState, useEffect, useRef, useCallback } = React;

/* ----------------------------- Brand Data ----------------------------- */
const BRAND = {
  name: "Harvard House Montessori",
  shortName: "Harvard House",
  established: "1985",
  tagline: "Pioneer in Early Education",
  website: "https://www.harvardhousem.com",
  websiteDisplay: "www.harvardhousem.com",
  liveUrl: "https://hhmcontact.pages.dev/",
  phone: "+91 98361 43663",
  phoneRaw: "+919836143663",
  whatsapp: "https://wa.me/919836143663",
  facebook: "https://www.facebook.com/p/Harvard-House-Montessori-61577379579392/",
  instagram: "https://www.instagram.com/harvardhousemontessori/",
  email: "HarvardHouseM@gmail.com",
  address: "21D/1A, Gorachand Road, near Don Bosco School, Kolkata - 700014",
  prospectus: "https://drive.google.com/file/d/1iUh5UH_vcbI86wIHNOkpvuXfnaImcetl/view?usp=sharing",
  maps: "https://maps.app.goo.gl/DNHHjwDfydrkrzEC8",
  logo: "https://res.cloudinary.com/dknjbns6k/image/upload/v1760507514/HHM_logo_qv351l.png",
};

/* ----------------------------- Helpers ----------------------------- */
// Brand SVG icons (Lucide CDN doesn't ship FB/IG by default)
const BrandIcon = ({ name, className = "w-5 h-5" }) => {
  if (name === "facebook") {
    return (
      <svg viewBox="0 0 24 24" fill="currentColor" className={className} aria-hidden="true">
        <path d="M22 12.06C22 6.5 17.52 2 12 2S2 6.5 2 12.06c0 5 3.66 9.15 8.44 9.94v-7.03H7.9v-2.91h2.54V9.84c0-2.52 1.49-3.91 3.78-3.91 1.1 0 2.24.2 2.24.2v2.47h-1.26c-1.24 0-1.63.78-1.63 1.57v1.88h2.78l-.45 2.91h-2.33V22c4.78-.79 8.43-4.94 8.43-9.94z"/>
      </svg>
    );
  }
  if (name === "instagram") {
    return (
      <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className={className} aria-hidden="true">
        <rect x="2" y="2" width="20" height="20" rx="5" ry="5"/>
        <path d="M16 11.37A4 4 0 1 1 12.63 8 4 4 0 0 1 16 11.37z"/>
        <line x1="17.5" y1="6.5" x2="17.51" y2="6.5"/>
      </svg>
    );
  }
  return null;
};

const Icon = ({ name, className = "w-5 h-5", strokeWidth = 2 }) => {
  if (name === "facebook" || name === "instagram") {
    return <BrandIcon name={name} className={className} />;
  }
  return React.createElement("i", {
    "data-lucide": name,
    className,
    style: { strokeWidth },
  });
};

const showToast = (msg) => {
  const el = document.getElementById("toast");
  if (!el) return;
  el.textContent = "";
  const iconSpan = document.createElement("span");
  iconSpan.innerHTML = "✓";
  iconSpan.style.fontWeight = "700";
  el.appendChild(iconSpan);
  el.appendChild(document.createTextNode(" " + msg));
  el.classList.add("show");
  clearTimeout(window.__toastTimer);
  window.__toastTimer = setTimeout(() => el.classList.remove("show"), 2200);
};

const downloadVCard = () => {
  const vcard = [
    "BEGIN:VCARD",
    "VERSION:3.0",
    `FN:${BRAND.name}`,
    `ORG:${BRAND.name}`,
    `TITLE:${BRAND.tagline}`,
    `TEL;TYPE=CELL,VOICE:${BRAND.phoneRaw}`,
    `TEL;TYPE=WORK,VOICE:${BRAND.phoneRaw}`,
    `EMAIL;TYPE=INTERNET,WORK:${BRAND.email}`,
    `URL:${BRAND.website}`,
    `ADR;TYPE=WORK:;;21D/1A Gorachand Road;Kolkata;West Bengal;700014;India`,
    `NOTE:${BRAND.tagline} — Established ${BRAND.established}`,
    `PHOTO;VALUE=URI:${BRAND.logo}`,
    "END:VCARD",
  ].join("\n");

  const blob = new Blob([vcard], { type: "text/vcard;charset=utf-8" });
  const url = URL.createObjectURL(blob);
  const a = document.createElement("a");
  a.href = url;
  a.download = "Harvard-House-Montessori.vcf";
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  URL.revokeObjectURL(url);
  try { localStorage.setItem("hhm_contact_saved", "1"); } catch {}
  showToast("Contact saved!");
};

// Download branded QR code (renders QR + logo onto canvas)
const downloadBrandedQR = () => {
  const canvas = document.getElementById("branded-qr-canvas");
  if (!canvas) { showToast("QR not ready"); return; }
  const link = document.createElement("a");
  link.download = "HHM-QR-Code.png";
  link.href = canvas.toDataURL("image/png");
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
  showToast("QR downloaded!");
};

const sharePage = async () => {
  const shareData = {
    title: BRAND.name,
    text: `${BRAND.name} — ${BRAND.tagline}. Estd. ${BRAND.established}.`,
    url: window.location.href,
  };
  if (navigator.share) {
    try {
      await navigator.share(shareData);
    } catch (e) {
      /* user cancelled */
    }
  } else {
    try {
      await navigator.clipboard.writeText(window.location.href);
      showToast("Link copied to clipboard!");
    } catch {
      showToast("Sharing not supported");
    }
  }
};

const copyPhone = async () => {
  try {
    await navigator.clipboard.writeText(BRAND.phone);
    showToast("Phone number copied!");
  } catch {
    showToast("Couldn't copy");
  }
};

/* ----------------------------- Hero ----------------------------- */
const Hero = () => (
  <header className="relative pt-10 pb-8 sm:pt-16 sm:pb-12 px-4 overflow-hidden">
    {/* Decorative blobs */}
    <div className="absolute top-0 left-1/4 w-72 h-72 bg-blue-200 rounded-full mix-blend-multiply filter blur-3xl opacity-30 animate-float" aria-hidden="true"></div>
    <div className="absolute top-20 right-1/4 w-72 h-72 bg-red-200 rounded-full mix-blend-multiply filter blur-3xl opacity-25 animate-float" style={{ animationDelay: "2s" }} aria-hidden="true"></div>

    <div className="relative max-w-3xl mx-auto text-center">
      {/* Established Ribbon */}
      <div className="inline-flex items-center gap-2 ribbon text-white text-xs sm:text-sm font-semibold px-4 py-1.5 rounded-full shadow-soft mb-6 reveal">
        <Icon name="award" className="w-4 h-4" />
        <span>Established 1985 · 40 Years of Excellence</span>
      </div>

      {/* Logo */}
      <div className="relative inline-block mb-6 reveal delay-1">
        <div className="logo-ring relative">
          <img
            src={BRAND.logo}
            alt="Harvard House Montessori Logo"
            className="logo-glow w-36 h-36 sm:w-44 sm:h-44 mx-auto rounded-full bg-white p-2 shadow-premium animate-float"
            loading="eager"
          />
        </div>
      </div>

      {/* Name */}
      <h1 className="font-display text-4xl sm:text-5xl md:text-6xl font-extrabold tracking-tight leading-tight reveal delay-2">
        <span className="gradient-text">Harvard House</span>
        <br />
        <span className="text-brand-navy">Montessori</span>
      </h1>

      {/* Tagline */}
      <p className="mt-4 text-base sm:text-lg text-slate-600 font-medium reveal delay-3">
        <span className="inline-block w-8 h-px bg-brand-red align-middle mr-2"></span>
        {BRAND.tagline}
        <span className="inline-block w-8 h-px bg-brand-red align-middle ml-2"></span>
      </p>

      {/* CTA Buttons */}
      <div className="mt-8 flex flex-wrap justify-center gap-3 reveal delay-4">
        <a
          href={`tel:${BRAND.phoneRaw}`}
          className="group relative inline-flex items-center gap-2 bg-brand-navy hover:bg-brand-navyDark text-white font-semibold px-6 py-3 rounded-full shadow-soft hover:shadow-premium transition-all duration-300"
        >
          <span className="pulse-ring text-blue-300"></span>
          <Icon name="phone" className="w-4 h-4" />
          Call Now
        </a>
        <a
          href={BRAND.whatsapp}
          target="_blank"
          rel="noopener noreferrer"
          className="inline-flex items-center gap-2 bg-green-600 hover:bg-green-700 text-white font-semibold px-6 py-3 rounded-full shadow-soft hover:shadow-premium transition-all duration-300"
        >
          <Icon name="message-circle" className="w-4 h-4" />
          WhatsApp
        </a>
        <a
          href={BRAND.website}
          target="_blank"
          rel="noopener noreferrer"
          className="inline-flex items-center gap-2 bg-white border-2 border-brand-navy text-brand-navy hover:bg-brand-navy hover:text-white font-semibold px-6 py-3 rounded-full shadow-soft hover:shadow-premium transition-all duration-300"
        >
          <Icon name="globe" className="w-4 h-4" />
          Website
        </a>
      </div>
    </div>
  </header>
);

/* ----------------------------- Smart Action Grid ----------------------------- */
const ACTIONS = [
  {
    label: "Call",
    icon: "phone",
    href: `tel:${BRAND.phoneRaw}`,
    bg: "from-blue-500 to-blue-700",
    text: "text-white",
  },
  {
    label: "WhatsApp",
    icon: "message-circle",
    href: BRAND.whatsapp,
    external: true,
    bg: "from-green-500 to-emerald-600",
    text: "text-white",
  },
  {
    label: "Email",
    icon: "mail",
    href: `mailto:${BRAND.email}`,
    bg: "from-rose-500 to-red-600",
    text: "text-white",
  },
  {
    label: "Website",
    icon: "globe",
    href: BRAND.website,
    external: true,
    bg: "from-indigo-500 to-blue-700",
    text: "text-white",
  },
  {
    label: "Facebook",
    icon: "facebook",
    href: BRAND.facebook,
    external: true,
    bg: "from-blue-600 to-blue-800",
    text: "text-white",
  },
  {
    label: "Instagram",
    icon: "instagram",
    href: BRAND.instagram,
    external: true,
    bg: "from-pink-500 via-fuchsia-500 to-orange-400",
    text: "text-white",
  },
  {
    label: "Prospectus",
    icon: "file-text",
    href: BRAND.prospectus,
    external: true,
    bg: "from-amber-500 to-orange-600",
    text: "text-white",
  },
  {
    label: "Directions",
    icon: "map-pin",
    href: BRAND.maps,
    external: true,
    bg: "from-teal-500 to-cyan-600",
    text: "text-white",
  },
];

const ActionGrid = () => (
  <section id="actions" className="px-4 py-10 sm:py-14">
    <div className="max-w-3xl mx-auto">
      <div className="text-center mb-8 reveal">
        <p className="text-xs font-semibold tracking-[0.2em] text-brand-red uppercase">Quick Actions</p>
        <h2 className="mt-2 font-display text-3xl sm:text-4xl font-bold text-brand-navy">
          Connect with Us
        </h2>
        <p className="mt-2 text-slate-600 text-sm sm:text-base">
          Tap any option to reach us instantly.
        </p>
      </div>

      <div className="grid grid-cols-2 sm:grid-cols-4 gap-3 sm:gap-4">
        {ACTIONS.map((a, i) => (
          <a
            key={a.label}
            href={a.href}
            target={a.external ? "_blank" : undefined}
            rel={a.external ? "noopener noreferrer" : undefined}
            className={`action-card reveal delay-${(i % 6) + 1} group flex flex-col items-center justify-center gap-3 bg-gradient-to-br ${a.bg} ${a.text} rounded-2xl p-5 shadow-soft hover:shadow-premium`}
            aria-label={a.label}
          >
            <div className="w-12 h-12 rounded-2xl bg-white/20 backdrop-blur-sm flex items-center justify-center group-hover:scale-110 group-hover:rotate-6 transition-transform duration-300">
              <Icon name={a.icon} className="w-6 h-6" strokeWidth={2.2} />
            </div>
            <span className="text-sm sm:text-base font-semibold tracking-wide">{a.label}</span>
          </a>
        ))}
      </div>
    </div>
  </section>
);

/* ----------------------------- About ----------------------------- */
const FEATURES = [
  {
    icon: "trophy",
    title: "40 Years Legacy",
    desc: "Trusted by generations since 1985 — a heritage of excellence in early childhood education.",
    color: "text-amber-600 bg-amber-50",
  },
  {
    icon: "shield-check",
    title: "Safe Environment",
    desc: "A nurturing, secure, and child-friendly campus where every child is cared for like family.",
    color: "text-emerald-600 bg-emerald-50",
  },
  {
    icon: "sparkles",
    title: "Holistic Growth",
    desc: "Mind, body & character — we shape confident, curious, and compassionate young learners.",
    color: "text-fuchsia-600 bg-fuchsia-50",
  },
  {
    icon: "gamepad-2",
    title: "Indoor Play Area",
    desc: "Spacious, safe and engaging indoor play zone for active learning and joyful play.",
    color: "text-blue-600 bg-blue-50",
  },
  {
    icon: "snowflake",
    title: "Air-Conditioned Classes",
    desc: "Comfortable, climate-controlled classrooms designed for distraction-free learning.",
    color: "text-cyan-600 bg-cyan-50",
  },
  {
    icon: "graduation-cap",
    title: "Montessori Method",
    desc: "Authentic Montessori curriculum that empowers self-paced, hands-on discovery.",
    color: "text-rose-600 bg-rose-50",
  },
];

const About = () => (
  <section id="about" className="px-4 py-12 sm:py-16 dots-bg">
    <div className="max-w-4xl mx-auto">
      <div className="text-center mb-10 reveal">
        <p className="text-xs font-semibold tracking-[0.2em] text-brand-red uppercase">About Us</p>
        <h2 className="mt-2 font-display text-3xl sm:text-4xl font-bold text-brand-navy">
          Where Little Minds <span className="gradient-text">Bloom</span>
        </h2>
        <p className="mt-3 text-slate-600 text-sm sm:text-base max-w-2xl mx-auto">
          For four decades, Harvard House Montessori has been a pioneer in early education in Kolkata —
          fostering curiosity, confidence, and character in every child we welcome.
        </p>
      </div>

      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4 sm:gap-5">
        {FEATURES.map((f, i) => (
          <div
            key={f.title}
            className={`reveal delay-${(i % 6) + 1} lift bg-white rounded-2xl p-5 sm:p-6 shadow-softer border border-slate-100`}
          >
            <div className={`w-12 h-12 rounded-xl flex items-center justify-center ${f.color} mb-4`}>
              <Icon name={f.icon} className="w-6 h-6" strokeWidth={2.2} />
            </div>
            <h3 className="font-display text-lg font-bold text-brand-navy mb-1.5">{f.title}</h3>
            <p className="text-sm text-slate-600 leading-relaxed">{f.desc}</p>
          </div>
        ))}
      </div>
    </div>
  </section>
);

/* ----------------------------- Contact Card ----------------------------- */
const ContactCard = () => (
  <section id="contact" className="px-4 py-12 sm:py-16">
    <div className="max-w-2xl mx-auto">
      <div className="text-center mb-8 reveal">
        <p className="text-xs font-semibold tracking-[0.2em] text-brand-red uppercase">Get in Touch</p>
        <h2 className="mt-2 font-display text-3xl sm:text-4xl font-bold text-brand-navy">
          Contact Information
        </h2>
      </div>

      <div className="premium-ring rounded-3xl shadow-premium overflow-hidden reveal delay-2">
        {/* Header strip */}
        <div className="ribbon px-6 py-5 flex items-center gap-4">
          <img src={BRAND.logo} alt="" className="w-14 h-14 rounded-full bg-white p-1 shadow-md" />
          <div className="text-white">
            <p className="font-display font-bold text-lg leading-tight">Harvard House Montessori</p>
            <p className="text-xs opacity-90">Estd. 1985 · {BRAND.tagline}</p>
          </div>
        </div>

        {/* Contact list */}
        <div className="bg-white p-2 sm:p-3">
          <ContactRow
            icon="phone"
            label="Phone"
            value={BRAND.phone}
            href={`tel:${BRAND.phoneRaw}`}
            actionIcon="copy"
            onAction={copyPhone}
            color="bg-blue-50 text-blue-600"
          />
          <ContactRow
            icon="mail"
            label="Email"
            value={BRAND.email}
            href={`mailto:${BRAND.email}`}
            color="bg-rose-50 text-rose-600"
          />
          <ContactRow
            icon="globe"
            label="Website"
            value={BRAND.websiteDisplay}
            href={BRAND.website}
            external
            color="bg-indigo-50 text-indigo-600"
          />
          <ContactRow
            icon="message-circle"
            label="WhatsApp"
            value={BRAND.phone}
            href={BRAND.whatsapp}
            external
            color="bg-emerald-50 text-emerald-600"
          />
          <ContactRow
            icon="map-pin"
            label="Address"
            value={BRAND.address}
            href={BRAND.maps}
            external
            color="bg-amber-50 text-amber-600"
            multiline
          />
        </div>

        {/* Save Contact CTA */}
        <div className="bg-gradient-to-br from-slate-50 to-blue-50 p-5 sm:p-6 border-t border-slate-100">
          <button
            onClick={downloadVCard}
            className="w-full group flex items-center justify-center gap-2 bg-brand-navy hover:bg-brand-navyDark text-white font-semibold py-3.5 rounded-2xl shadow-soft hover:shadow-premium transition-all duration-300"
          >
            <Icon name="user-plus" className="w-5 h-5 group-hover:scale-110 transition-transform" />
            Save to Contacts
          </button>
        </div>
      </div>
    </div>
  </section>
);

const ContactRow = ({ icon, label, value, href, external, actionIcon, onAction, color, multiline }) => (
  <div className="flex items-center gap-3 sm:gap-4 p-3 sm:p-4 rounded-xl hover:bg-slate-50 transition-colors group">
    <div className={`shrink-0 w-11 h-11 sm:w-12 sm:h-12 rounded-xl flex items-center justify-center ${color}`}>
      <Icon name={icon} className="w-5 h-5" strokeWidth={2.2} />
    </div>
    <a
      href={href}
      target={external ? "_blank" : undefined}
      rel={external ? "noopener noreferrer" : undefined}
      className="flex-1 min-w-0"
    >
      <p className="text-[11px] font-semibold tracking-wider text-slate-400 uppercase">{label}</p>
      <p className={`text-sm sm:text-base font-medium text-brand-navy group-hover:text-brand-red transition-colors ${multiline ? "leading-snug" : "truncate"}`}>
        {value}
      </p>
    </a>
    {actionIcon && (
      <button
        onClick={onAction}
        className="shrink-0 w-9 h-9 rounded-lg flex items-center justify-center text-slate-400 hover:text-brand-navy hover:bg-blue-50 transition-colors"
        aria-label={`Copy ${label}`}
      >
        <Icon name={actionIcon} className="w-4 h-4" />
      </button>
    )}
  </div>
);

/* ----------------------------- Footer ----------------------------- */
const Footer = () => (
  <footer className="px-4 pt-10 pb-8 mt-6 bg-gradient-to-b from-transparent to-slate-100">
    <div className="max-w-2xl mx-auto">
      {/* Action bar */}
      <div className="grid grid-cols-2 gap-3 mb-8 reveal">
        <button
          onClick={sharePage}
          className="flex items-center justify-center gap-2 bg-white border-2 border-brand-navy text-brand-navy hover:bg-brand-navy hover:text-white font-semibold py-3 rounded-2xl shadow-softer transition-all duration-300"
        >
          <Icon name="share-2" className="w-4 h-4" />
          Share
        </button>
        <button
          onClick={downloadVCard}
          className="flex items-center justify-center gap-2 bg-brand-red hover:bg-brand-redDark text-white font-semibold py-3 rounded-2xl shadow-soft transition-all duration-300"
        >
          <Icon name="download" className="w-4 h-4" />
          Save Contact
        </button>
      </div>

      {/* Social icons */}
      <div className="flex justify-center gap-3 mb-6 reveal delay-1">
        <a href={BRAND.facebook} target="_blank" rel="noopener noreferrer" aria-label="Facebook"
          className="w-10 h-10 rounded-full bg-white shadow-softer flex items-center justify-center text-blue-700 hover:scale-110 hover:shadow-soft transition">
          <Icon name="facebook" className="w-5 h-5" />
        </a>
        <a href={BRAND.instagram} target="_blank" rel="noopener noreferrer" aria-label="Instagram"
          className="w-10 h-10 rounded-full bg-white shadow-softer flex items-center justify-center text-pink-600 hover:scale-110 hover:shadow-soft transition">
          <Icon name="instagram" className="w-5 h-5" />
        </a>
        <a href={BRAND.whatsapp} target="_blank" rel="noopener noreferrer" aria-label="WhatsApp"
          className="w-10 h-10 rounded-full bg-white shadow-softer flex items-center justify-center text-green-600 hover:scale-110 hover:shadow-soft transition">
          <Icon name="message-circle" className="w-5 h-5" />
        </a>
        <a href={`mailto:${BRAND.email}`} aria-label="Email"
          className="w-10 h-10 rounded-full bg-white shadow-softer flex items-center justify-center text-rose-600 hover:scale-110 hover:shadow-soft transition">
          <Icon name="mail" className="w-5 h-5" />
        </a>
      </div>

      {/* Brand mark */}
      <div className="flex items-center justify-center gap-3 mb-4 reveal delay-2">
        <img src={BRAND.logo} alt="" className="w-10 h-10 rounded-full bg-white p-1 shadow-softer" />
        <div className="text-left">
          <p className="font-display font-bold text-brand-navy text-sm leading-tight">Harvard House Montessori</p>
          <p className="text-[11px] text-slate-500">Pioneer in Early Education · Estd. 1985</p>
        </div>
      </div>

      <p className="text-center text-xs text-slate-500 reveal delay-3">
        © {new Date().getFullYear()} Harvard House Montessori. All rights reserved.
      </p>
      <p className="text-center text-[11px] text-slate-400 mt-1 reveal delay-3">
        Made with <span className="text-brand-red">♥</span> for little learners.
      </p>
    </div>
  </footer>
);

/* ----------------------------- QR Section ----------------------------- */
const QRSection = () => {
  const canvasRef = useRef(null);
  const [ready, setReady] = useState(false);

  // Compose branded QR (logo overlaid on real scannable QR) onto canvas
  useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas) return;
    const ctx = canvas.getContext("2d");
    const SIZE = 800;
    canvas.width = SIZE;
    canvas.height = SIZE;

    const qrImg = new Image();
    qrImg.crossOrigin = "anonymous";
    const logoImg = new Image();
    logoImg.crossOrigin = "anonymous";

    let qrLoaded = false, logoLoaded = false;
    const tryDraw = () => {
      if (!qrLoaded || !logoLoaded) return;

      // White background
      ctx.fillStyle = "#ffffff";
      ctx.fillRect(0, 0, SIZE, SIZE);

      // Draw QR code
      ctx.drawImage(qrImg, 0, 0, SIZE, SIZE);

      // White rounded square behind logo (so QR ECC-H still scans)
      const logoSize = SIZE * 0.22;
      const cx = SIZE / 2;
      const cy = SIZE / 2;
      const padBoxSize = logoSize + 24;
      const x = cx - padBoxSize / 2;
      const y = cy - padBoxSize / 2;
      const r = 22;
      ctx.fillStyle = "#ffffff";
      ctx.beginPath();
      ctx.moveTo(x + r, y);
      ctx.lineTo(x + padBoxSize - r, y);
      ctx.quadraticCurveTo(x + padBoxSize, y, x + padBoxSize, y + r);
      ctx.lineTo(x + padBoxSize, y + padBoxSize - r);
      ctx.quadraticCurveTo(x + padBoxSize, y + padBoxSize, x + padBoxSize - r, y + padBoxSize);
      ctx.lineTo(x + r, y + padBoxSize);
      ctx.quadraticCurveTo(x, y + padBoxSize, x, y + padBoxSize - r);
      ctx.lineTo(x, y + r);
      ctx.quadraticCurveTo(x, y, x + r, y);
      ctx.closePath();
      ctx.fill();

      // Subtle border
      ctx.strokeStyle = "rgba(30, 58, 138, 0.12)";
      ctx.lineWidth = 2;
      ctx.stroke();

      // Draw logo centered
      ctx.drawImage(logoImg, cx - logoSize / 2, cy - logoSize / 2, logoSize, logoSize);

      setReady(true);
    };

    qrImg.onload = () => { qrLoaded = true; tryDraw(); };
    logoImg.onload = () => { logoLoaded = true; tryDraw(); };
    qrImg.onerror = () => console.warn("QR failed to load");
    logoImg.onerror = () => console.warn("Logo failed to load");

    // High error-correction QR pointing to live URL
    const qrUrl = `https://api.qrserver.com/v1/create-qr-code/?data=${encodeURIComponent(BRAND.liveUrl)}&size=${SIZE}x${SIZE}&margin=20&ecc=H&color=1e3a8a&bgcolor=ffffff`;
    qrImg.src = qrUrl;
    logoImg.src = BRAND.logo;
  }, []);

  return (
    <section id="qr" className="px-4 py-12 sm:py-16">
      <div className="max-w-2xl mx-auto">
        <div className="text-center mb-8 reveal">
          <p className="text-xs font-semibold tracking-[0.2em] text-brand-red uppercase">Scan & Connect</p>
          <h2 className="mt-2 font-display text-3xl sm:text-4xl font-bold text-brand-navy">
            Branded <span className="gradient-text">QR Code</span>
          </h2>
          <p className="mt-2 text-slate-600 text-sm sm:text-base">
            Scan with any phone camera to instantly open this digital card.
          </p>
        </div>

        <div className="premium-ring rounded-3xl bg-white shadow-premium p-6 sm:p-8 reveal delay-1">
          <div className="relative mx-auto w-full max-w-xs sm:max-w-sm aspect-square bg-white rounded-2xl overflow-hidden">
            {!ready && (
              <div className="absolute inset-0 flex items-center justify-center bg-slate-50 rounded-2xl">
                <div className="w-10 h-10 border-4 border-brand-navy/20 border-t-brand-navy rounded-full animate-spin"></div>
              </div>
            )}
            <canvas
              ref={canvasRef}
              id="branded-qr-canvas"
              className={`w-full h-full transition-opacity duration-700 ${ready ? "opacity-100" : "opacity-0"}`}
              aria-label="Branded QR code for Harvard House Montessori"
            />
            {/* Decorative corners */}
            <span className="pointer-events-none absolute top-2 left-2 w-6 h-6 border-t-4 border-l-4 border-brand-navy rounded-tl-lg"></span>
            <span className="pointer-events-none absolute top-2 right-2 w-6 h-6 border-t-4 border-r-4 border-brand-red rounded-tr-lg"></span>
            <span className="pointer-events-none absolute bottom-2 left-2 w-6 h-6 border-b-4 border-l-4 border-brand-red rounded-bl-lg"></span>
            <span className="pointer-events-none absolute bottom-2 right-2 w-6 h-6 border-b-4 border-r-4 border-brand-navy rounded-br-lg"></span>
          </div>

          <p className="mt-5 text-center text-sm text-slate-500">
            <span className="font-mono text-xs text-brand-navy break-all">{BRAND.liveUrl}</span>
          </p>

          <button
            onClick={downloadBrandedQR}
            disabled={!ready}
            className="mt-5 w-full group flex items-center justify-center gap-2 bg-brand-navy hover:bg-brand-navyDark disabled:opacity-50 disabled:cursor-wait text-white font-semibold py-3.5 rounded-2xl shadow-soft hover:shadow-premium transition-all duration-300"
          >
            <Icon name="download" className="w-5 h-5 group-hover:translate-y-0.5 transition-transform" />
            Download QR Code
          </button>
          <p className="mt-3 text-center text-[11px] text-slate-400">
            Place this QR on prospectus, business cards, signage & social bios.
          </p>
        </div>
      </div>
    </section>
  );
};

/* ----------------------------- Save Contact Modal (5s auto-popup) ----------------------------- */
const SaveContactModal = () => {
  const [open, setOpen] = useState(false);

  useEffect(() => {
    let dismissed = false;
    try { dismissed = localStorage.getItem("hhm_modal_dismissed") === "1"; } catch {}
    if (dismissed) return;
    const t = setTimeout(() => setOpen(true), 5000);
    return () => clearTimeout(t);
  }, []);

  const close = useCallback(() => {
    setOpen(false);
    try { localStorage.setItem("hhm_modal_dismissed", "1"); } catch {}
  }, []);

  const handleSave = () => {
    downloadVCard();
    close();
  };

  // Re-init lucide icons when modal opens
  useEffect(() => {
    if (open && window.lucide) window.lucide.createIcons();
  }, [open]);

  // ESC to close
  useEffect(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === "Escape") close(); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [open, close]);

  if (!open) return null;

  return (
    <div
      className="modal-overlay"
      role="dialog"
      aria-modal="true"
      aria-labelledby="save-modal-title"
      onClick={close}
    >
      <div className="modal-card" onClick={(e) => e.stopPropagation()}>
        <button
          onClick={close}
          aria-label="Close"
          className="absolute top-3 right-3 w-9 h-9 rounded-full bg-slate-100 hover:bg-slate-200 text-slate-500 hover:text-slate-800 flex items-center justify-center transition"
        >
          <Icon name="x" className="w-4 h-4" />
        </button>

        <div className="flex flex-col items-center text-center px-6 pt-7 pb-6">
          <div className="relative mb-4">
            <div className="absolute inset-0 bg-gradient-to-br from-brand-navy to-brand-red rounded-full blur-xl opacity-30 animate-pulse"></div>
            <img
              src={BRAND.logo}
              alt=""
              className="relative w-20 h-20 rounded-full bg-white p-1 shadow-premium"
            />
          </div>

          <h3 id="save-modal-title" className="font-display text-2xl font-bold text-brand-navy">
            Save Our Contact?
          </h3>
          <p className="mt-2 text-sm text-slate-600 leading-relaxed">
            Add <span className="font-semibold text-brand-navy">Harvard House Montessori</span> to your phone contacts so you can reach us anytime.
          </p>

          <div className="mt-5 grid grid-cols-2 gap-2 w-full text-left">
            <div className="flex items-center gap-2 text-xs text-slate-600 bg-slate-50 rounded-lg px-3 py-2">
              <Icon name="phone" className="w-3.5 h-3.5 text-brand-navy" />
              <span>Direct call</span>
            </div>
            <div className="flex items-center gap-2 text-xs text-slate-600 bg-slate-50 rounded-lg px-3 py-2">
              <Icon name="mail" className="w-3.5 h-3.5 text-brand-red" />
              <span>Email ready</span>
            </div>
            <div className="flex items-center gap-2 text-xs text-slate-600 bg-slate-50 rounded-lg px-3 py-2">
              <Icon name="map-pin" className="w-3.5 h-3.5 text-emerald-600" />
              <span>Location saved</span>
            </div>
            <div className="flex items-center gap-2 text-xs text-slate-600 bg-slate-50 rounded-lg px-3 py-2">
              <Icon name="globe" className="w-3.5 h-3.5 text-indigo-600" />
              <span>Website link</span>
            </div>
          </div>

          <button
            onClick={handleSave}
            className="mt-6 w-full group flex items-center justify-center gap-2 bg-brand-navy hover:bg-brand-navyDark text-white font-semibold py-3.5 rounded-2xl shadow-soft hover:shadow-premium transition-all duration-300"
          >
            <Icon name="user-plus" className="w-5 h-5 group-hover:scale-110 transition-transform" />
            Save to Contacts
          </button>
          <button
            onClick={close}
            className="mt-2 w-full text-xs text-slate-400 hover:text-slate-600 py-2 transition"
          >
            Maybe later
          </button>
        </div>
      </div>
    </div>
  );
};

/* ----------------------------- Floating Call FAB ----------------------------- */
const CallFAB = () => {
  const [show, setShow] = useState(false);
  useEffect(() => {
    const onScroll = () => setShow(window.scrollY > 400);
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  if (!show) return null;
  return (
    <a
      href={`tel:${BRAND.phoneRaw}`}
      className="fab w-14 h-14 rounded-full bg-brand-red hover:bg-brand-redDark text-white flex items-center justify-center shadow-premium animate-fade-in"
      aria-label="Call now"
    >
      <span className="pulse-ring text-red-300"></span>
      <Icon name="phone" className="w-6 h-6" strokeWidth={2.4} />
    </a>
  );
};

/* ----------------------------- Toast container ----------------------------- */
const Toast = () => <div id="toast" className="toast" role="status" aria-live="polite"></div>;

/* ----------------------------- App ----------------------------- */
const App = () => {
  useEffect(() => {
    // Initialize Lucide icons after each render
    if (window.lucide) window.lucide.createIcons();
  });

  useEffect(() => {
    // Reveal-on-scroll observer
    const observer = new IntersectionObserver(
      (entries) => {
        entries.forEach((e) => {
          if (e.isIntersecting) {
            e.target.classList.add("visible");
            observer.unobserve(e.target);
          }
        });
      },
      { threshold: 0.12, rootMargin: "0px 0px -40px 0px" }
    );
    document.querySelectorAll(".reveal").forEach((el) => observer.observe(el));
    return () => observer.disconnect();
  });

  return (
    <main>
      <Hero />
      <ActionGrid />
      <About />
      <ContactCard />
      <QRSection />
      <Footer />
      <CallFAB />
      <SaveContactModal />
      <Toast />
    </main>
  );
};

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