/* ════════════════════════════════════════════════════════════════
   Green Harvest — shared components (React 18 + Framer Motion 11)
   ════════════════════════════════════════════════════════════════ */

const { useEffect, useRef, useState } = React;

// Framer Motion: prefer window.Motion (UMD default), fall back to FramerMotion if present.
const _FM = window.Motion || window.FramerMotion || {};
const motion = _FM.motion || (function() {
  // Safe fallback: render the underlying tag with no animation
  const create = (tag) => React.forwardRef((props, ref) => {
    const { initial, animate, exit, transition, whileInView, viewport, ...rest } = props;
    return React.createElement(tag, { ref, ...rest }, props.children);
  });
  const proxy = new Proxy({}, { get: (_, tag) => create(tag) });
  return proxy;
})();

/* ─── Suppress benign FM warnings ─── */
const _origError = console.error;
console.error = (...args) => {
  const msg = (args[0] || "").toString();
  if (msg.includes("Each child in a list") || msg.includes("unique \"key\" prop")) return;
  return _origError.apply(console, args);
};

/* ─── Icons (lucide-style + material) ─── */
const ArrowUpRight = ({ className = "h-5 w-5" }) => (
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className={className}>
    <path d="M7 17L17 7"/>
    <path d="M7 7h10v10"/>
  </svg>
);
const PlayIcon = ({ className = "h-4 w-4" }) => (
  <svg viewBox="0 0 24 24" fill="currentColor" className={className}>
    <polygon points="6 4 20 12 6 20 6 4"/>
  </svg>
);
const ClockIcon = ({ className = "h-7 w-7" }) => (
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" className={className}>
    <circle cx="12" cy="12" r="9"/>
    <path d="M12 7v5l3 2" strokeLinecap="round"/>
  </svg>
);
const GlobeIcon = ({ className = "h-7 w-7" }) => (
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" className={className}>
    <circle cx="12" cy="12" r="9"/>
    <path d="M3 12h18M12 3a13 13 0 0 1 0 18M12 3a13 13 0 0 0 0 18" strokeLinecap="round"/>
  </svg>
);
const LeafIcon = ({ className = "h-6 w-6" }) => (
  <svg viewBox="0 0 24 24" fill="currentColor" className={className}>
    <path d="M17 8C8 10 5.9 16.17 3.82 21.34l1.85-1.83C8.16 19.5 12.21 18.13 14 16c1.31-1.57 1.83-3.84 3-8z"/>
  </svg>
);
const ShipIcon = ({ className = "h-6 w-6" }) => (
  <svg viewBox="0 0 24 24" fill="currentColor" className={className}>
    <path d="M20 21c-1.39 0-2.78-.47-4-1.32-2.44 1.71-5.56 1.71-8 0C6.78 20.53 5.39 21 4 21H2v2h2c1.38 0 2.74-.35 4-.99a8.13 8.13 0 0 0 8 0c1.26.65 2.62.99 4 .99h2v-2h-2zM3.95 19H4c1.6 0 3.02-.88 4-2 .98 1.12 2.4 2 4 2s3.02-.88 4-2c.98 1.12 2.4 2 4 2h.05l1.89-6.68c.08-.26.06-.54-.06-.78s-.34-.42-.6-.5L20 10.62V6c0-1.1-.9-2-2-2h-3V1H9v3H6c-1.1 0-2 .9-2 2v4.62l-1.29.42a1.007 1.007 0 0 0-.66 1.28L3.95 19zM6 6h12v3.97L12 8 6 9.97V6z"/>
  </svg>
);
const SparkleIcon = ({ className = "h-6 w-6" }) => (
  <svg viewBox="0 0 24 24" fill="currentColor" className={className}>
    <path d="M12 2L13.5 8.5L20 10L13.5 11.5L12 18L10.5 11.5L4 10L10.5 8.5L12 2zM19 16L19.6 18.4L22 19L19.6 19.6L19 22L18.4 19.6L16 19L18.4 18.4L19 16z"/>
  </svg>
);
const PhoneIcon = ({ className = "h-5 w-5" }) => (
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" className={className}>
    <path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z"/>
  </svg>
);
const MailIcon = ({ className = "h-5 w-5" }) => (
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" className={className}>
    <path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z"/>
    <polyline points="22,6 12,13 2,6"/>
  </svg>
);
const PinIcon = ({ className = "h-5 w-5" }) => (
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" className={className}>
    <path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0z"/>
    <circle cx="12" cy="10" r="3"/>
  </svg>
);

Object.assign(window, { ArrowUpRight, PlayIcon, ClockIcon, GlobeIcon, LeafIcon, ShipIcon, SparkleIcon, PhoneIcon, MailIcon, PinIcon });

/* ─── FadingVideo (custom rAF crossfade) ─── */
function FadingVideo({ src, className = "", style = {}, focalTop = false }) {
  const videoRef = useRef(null);
  const rafRef = useRef(null);
  const fadingOutRef = useRef(false);

  useEffect(() => {
    const video = videoRef.current;
    if (!video) return;

    const FADE_MS = 500;
    const FADE_OUT_LEAD = 0.55;

    const fadeTo = (target, duration = FADE_MS) => {
      if (rafRef.current) cancelAnimationFrame(rafRef.current);
      const startOpacity = parseFloat(video.style.opacity || "0");
      const startTime = performance.now();
      const step = (now) => {
        const t = Math.min(1, (now - startTime) / duration);
        const cur = startOpacity + (target - startOpacity) * t;
        video.style.opacity = cur.toString();
        if (t < 1) rafRef.current = requestAnimationFrame(step);
      };
      rafRef.current = requestAnimationFrame(step);
    };

    const onLoaded = () => {
      video.style.opacity = "0";
      video.play().catch(() => {});
      fadeTo(1);
    };
    const onTimeUpdate = () => {
      if (fadingOutRef.current) return;
      if (!video.duration) return;
      const remaining = video.duration - video.currentTime;
      if (remaining <= FADE_OUT_LEAD && remaining > 0) {
        fadingOutRef.current = true;
        fadeTo(0);
      }
    };
    const onEnded = () => {
      video.style.opacity = "0";
      setTimeout(() => {
        video.currentTime = 0;
        video.play().catch(() => {});
        fadingOutRef.current = false;
        fadeTo(1);
      }, 100);
    };

    video.style.opacity = "0";
    video.addEventListener("loadeddata", onLoaded);
    video.addEventListener("timeupdate", onTimeUpdate);
    video.addEventListener("ended", onEnded);

    return () => {
      if (rafRef.current) cancelAnimationFrame(rafRef.current);
      video.removeEventListener("loadeddata", onLoaded);
      video.removeEventListener("timeupdate", onTimeUpdate);
      video.removeEventListener("ended", onEnded);
    };
  }, [src]);

  return (
    <video
      ref={videoRef}
      autoPlay
      muted
      playsInline
      preload="auto"
      className={className}
      style={{ opacity: 0, ...style }}
      src={src}
    />
  );
}

/* ─── BlurText (word-by-word blur-in via Motion) ─── */
function BlurText({ text, className = "", stagger = 100 }) {
  const [visible, setVisible] = useState(false);
  const containerRef = useRef(null);

  useEffect(() => {
    if (!containerRef.current) return;
    const observer = new IntersectionObserver(
      (entries) => entries.forEach(e => e.isIntersecting && setVisible(true)),
      { threshold: 0.1 }
    );
    observer.observe(containerRef.current);
    return () => observer.disconnect();
  }, []);

  const words = text.split(" ");
  return (
    <p
      ref={containerRef}
      className={className}
      style={{ display: "flex", flexWrap: "wrap", justifyContent: "center", rowGap: "0.1em" }}
    >
      {words.map((w, i) => (
        <motion.span
          key={i}
          initial={{ filter: "blur(10px)", opacity: 0, y: 50 }}
          animate={visible ? {
            filter: ["blur(10px)", "blur(5px)", "blur(0px)"],
            opacity: [0, 0.5, 1],
            y: [50, -5, 0],
          } : {}}
          transition={{
            duration: 0.7,
            times: [0, 0.5, 1],
            ease: "easeOut",
            delay: (i * stagger) / 1000,
          }}
          style={{ display: "inline-block", marginRight: "0.28em" }}
        >
          {w}
        </motion.span>
      ))}
    </p>
  );
}

/* ─── Navbar ─── */
function Navbar({ active }) {
  const links = [
    { label: "Home", href: "../index.html#home", key: "home" },
    { label: "Harvest", href: "../index.html#harvest", key: "harvest" },
    { label: "Products", href: "../index.html#products", key: "products" },
    { label: "Origin", href: "../index.html#origin", key: "origin" },
    { label: "Contact", href: "../index.html#contact", key: "contact" },
  ];
  return (
    <nav className="fixed top-4 left-0 right-0 z-50 px-4 sm:px-8 lg:px-16 flex items-center justify-between">
      <a href="../index.html" className="liquid-glass flex items-center justify-center" style={{width: 48, height: 48, borderRadius: 9999}}>
        <span className="font-heading italic text-white" style={{ fontSize: 26, lineHeight: 1 }}>g</span>
      </a>
      <div className="liquid-glass hidden lg:flex items-center" style={{ borderRadius: 9999, padding: 6 }}>
        {links.map(l => (
          <a key={l.key} href={l.href}
             className={`px-3 py-2 text-sm font-medium font-body ${active === l.key ? "text-white" : "text-white/90 hover:text-white"}`}>
            {l.label}
          </a>
        ))}
        <a href="../index.html#contact" className="ml-2 inline-flex items-center gap-1.5 bg-white text-black whitespace-nowrap px-4 py-2 text-sm font-medium" style={{ borderRadius: 9999 }}>
          Request Quote <ArrowUpRight className="h-4 w-4" />
        </a>
      </div>
      <a href="../index.html#contact" className="lg:hidden bg-white text-black px-4 py-2 text-xs font-medium" style={{ borderRadius: 9999 }}>
        Quote
      </a>
    </nav>
  );
}

/* For pages at root (index.html), Navbar without `../` prefix */
function NavbarRoot({ active }) {
  const links = [
    { label: "Home", href: "#home", key: "home" },
    { label: "Harvest", href: "#harvest", key: "harvest" },
    { label: "Products", href: "#products", key: "products" },
    { label: "Origin", href: "#origin", key: "origin" },
    { label: "Contact", href: "#contact", key: "contact" },
  ];
  return (
    <nav className="fixed top-4 left-0 right-0 z-50 px-4 sm:px-8 lg:px-16 flex items-center justify-between">
      <a href="#home" className="liquid-glass flex items-center justify-center" style={{width: 48, height: 48, borderRadius: 9999}}>
        <span className="font-heading italic text-white" style={{ fontSize: 26, lineHeight: 1 }}>g</span>
      </a>
      <div className="liquid-glass hidden lg:flex items-center" style={{ borderRadius: 9999, padding: 6 }}>
        {links.map(l => (
          <a key={l.key} href={l.href}
             className={`px-3 py-2 text-sm font-medium font-body ${active === l.key ? "text-white" : "text-white/90 hover:text-white"}`}>
            {l.label}
          </a>
        ))}
        <a href="#contact" className="ml-2 inline-flex items-center gap-1.5 bg-white text-black whitespace-nowrap px-4 py-2 text-sm font-medium" style={{ borderRadius: 9999 }}>
          Request Quote <ArrowUpRight className="h-4 w-4" />
        </a>
      </div>
      <a href="#contact" className="lg:hidden bg-white text-black px-4 py-2 text-xs font-medium" style={{ borderRadius: 9999 }}>
        Quote
      </a>
    </nav>
  );
}

/* ─── Footer ─── */
function Footer() {
  return (
    <footer className="relative bg-black border-t border-white/10 pt-20 pb-12 px-4 sm:px-8 lg:px-16">
      <div className="max-w-7xl mx-auto">
        <div className="grid grid-cols-1 md:grid-cols-4 gap-12">
          <div>
            <div className="flex items-center gap-3 mb-6">
              <div className="liquid-glass flex items-center justify-center" style={{width: 44, height: 44, borderRadius: 9999}}>
                <span className="font-heading italic text-white" style={{ fontSize: 24, lineHeight: 1 }}>g</span>
              </div>
              <div>
                <div className="font-heading italic text-white text-2xl">GreenHarvest</div>
                <div className="text-[10px] text-white/60 tracking-[0.3em] uppercase font-body">Agro Export Ltd.</div>
              </div>
            </div>
            <p className="text-sm text-white/60 font-body font-light leading-snug max-w-[28ch]">
              A trusted bridge between the Nigerian harvest and the world's most discerning importers.
            </p>
          </div>
          <div>
            <div className="text-[10px] text-white/50 tracking-[0.3em] uppercase font-body mb-4">Navigate</div>
            <ul className="space-y-2 font-body text-sm">
              <li><a href="../index.html#harvest" className="text-white/80 hover:text-white">Harvest</a></li>
              <li><a href="../index.html#products" className="text-white/80 hover:text-white">Products</a></li>
              <li><a href="../index.html#origin" className="text-white/80 hover:text-white">Origin</a></li>
              <li><a href="../index.html#contact" className="text-white/80 hover:text-white">Contact</a></li>
            </ul>
          </div>
          <div>
            <div className="text-[10px] text-white/50 tracking-[0.3em] uppercase font-body mb-4">Products</div>
            <ul className="space-y-2 font-body text-sm">
              <li><a href="../products/sesame.html" className="text-white/80 hover:text-white">Sesame Seeds</a></li>
              <li><a href="../products/hibiscus.html" className="text-white/80 hover:text-white">Hibiscus Flower</a></li>
              <li><a href="../products/cashew.html" className="text-white/80 hover:text-white">Cashew Nuts</a></li>
              <li><a href="../products/cocoa.html" className="text-white/80 hover:text-white">Cocoa Beans</a></li>
              <li><a href="../products/ginger.html" className="text-white/80 hover:text-white">Ginger</a></li>
              <li><a href="../products/shea.html" className="text-white/80 hover:text-white">Shea Butter</a></li>
              <li><a href="../products/soybeans.html" className="text-white/80 hover:text-white">Soybeans</a></li>
              <li><a href="../products/palm-kernel.html" className="text-white/80 hover:text-white">Palm Kernel</a></li>
            </ul>
          </div>
          <div>
            <div className="text-[10px] text-white/50 tracking-[0.3em] uppercase font-body mb-4">Contact</div>
            <ul className="space-y-3 font-body text-sm">
              <li className="flex items-start gap-2"><PinIcon className="h-4 w-4 mt-0.5 shrink-0 text-white/60"/><span className="text-white/80">Plot 24, Marina Business District<br/>Lagos, Nigeria</span></li>
              <li className="flex items-center gap-2"><PhoneIcon className="h-4 w-4 text-white/60"/><a href="tel:+2348012345678" className="text-white/80 hover:text-white">+234 801 234 5678</a></li>
              <li className="flex items-center gap-2"><MailIcon className="h-4 w-4 text-white/60"/><a href="mailto:info@greenharvestagroexport.com" className="text-white/80 hover:text-white break-all">info@greenharvestagroexport.com</a></li>
            </ul>
          </div>
        </div>
        <div className="mt-16 pt-8 border-t border-white/10 flex flex-col md:flex-row items-center justify-between gap-4">
          <div className="text-xs text-white/40 font-body tracking-[0.15em]">
            © MMXXVI · GREENHARVEST AGRO EXPORT LTD. · LAGOS · NIGERIA
          </div>
          <div className="text-xs text-white/40 font-body tracking-[0.15em]">
            Sourced at origin · Shipped with conviction
          </div>
        </div>
        <div className="mt-6 pt-5 border-t border-white/[0.06] text-center">
          <a href="https://eximnext.com" target="_blank" rel="noopener" className="text-[10px] text-white/30 font-body tracking-[0.2em] uppercase hover:text-white/50 transition-colors">
            Managed &amp; Developed by <span className="text-white/45">EximNext.com</span>
          </a>
        </div>
      </div>
    </footer>
  );
}

Object.assign(window, { FadingVideo, BlurText, Navbar, NavbarRoot, Footer });

/* ============================================================
   CallButton — Call Now (instant) + Schedule for Later (appointment)
   ============================================================ */
function CallButton({
  company = "GreenHarvest Agro Export Ltd.",
  owner = "Mr. Adebayo Okonkwo",
  callEndpoint = "call.php",
  bookEndpoint = "book.php",
  slotsEndpoint = "slots.php",
} = {}) {
  const [open, setOpen] = useState(false);
  const [tab, setTab] = useState("now"); // "now" | "schedule"

  // ---- Call Now state ----
  const [stage, setStage] = useState("idle"); // idle|dialing|ringing|connected|error
  const [room, setRoom] = useState("");
  const [video, setVideo] = useState(true);
  const [visitorName, setVisitorName] = useState("");
  const [errorMsg, setErrorMsg] = useState("");
  const ringSecRef = useRef(0);
  const [ringSec, setRingSec] = useState(0);
  const tickerRef = useRef(null);

  // ---- Schedule state ----
  const [slotsData, setSlotsData] = useState(null);  // {days:[...]}
  const [loadingSlots, setLoadingSlots] = useState(false);
  const [pickedDate, setPickedDate] = useState(null);
  const [pickedTime, setPickedTime] = useState(null);
  const [bookName, setBookName] = useState("");
  const [bookEmail, setBookEmail] = useState("");
  const [bookStage, setBookStage] = useState("pick"); // pick|submitting|confirmed|error
  const [bookConfirmation, setBookConfirmation] = useState(null);
  const [bookError, setBookError] = useState("");

  function makeRoom() {
    return "greenharvest-" + Math.random().toString(36).slice(2, 8) + "-" + Date.now().toString(36);
  }

  async function startCall() {
    setErrorMsg("");
    setStage("dialing");
    const r = makeRoom();
    setRoom(r);
    try {
      const res = await fetch(callEndpoint, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ room: r, video, visitorName: visitorName.trim(), company, owner }),
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok || !data.ok) throw new Error(data.error || ("HTTP " + res.status));
      setStage("ringing");
      ringSecRef.current = 0;
      setRingSec(0);
      tickerRef.current = setInterval(() => {
        ringSecRef.current += 1;
        setRingSec(ringSecRef.current);
      }, 1000);
    } catch (e) {
      setErrorMsg(e.message || "Could not place call");
      setStage("error");
    }
  }

  function endCall() {
    if (tickerRef.current) { clearInterval(tickerRef.current); tickerRef.current = null; }
    setStage("idle");
    setRoom("");
    setRingSec(0);
    // Reset schedule too
    setBookStage("pick");
    setBookConfirmation(null);
    setBookError("");
    setPickedDate(null);
    setPickedTime(null);
    setOpen(false);
  }

  useEffect(() => () => {
    if (tickerRef.current) clearInterval(tickerRef.current);
  }, []);

  // Visitor auto-joins Jitsi 1.5s after ringing starts
  useEffect(() => {
    if (stage === "ringing") {
      const t = setTimeout(() => setStage("connected"), 1500);
      return () => clearTimeout(t);
    }
  }, [stage]);

  // Lazy-load slots when user opens Schedule tab
  useEffect(() => {
    if (open && tab === "schedule" && slotsData == null && !loadingSlots) {
      setLoadingSlots(true);
      fetch(slotsEndpoint)
        .then(r => r.json())
        .then(d => { setSlotsData(d); setLoadingSlots(false); if (d?.days?.[0]) setPickedDate(d.days[0].date); })
        .catch(() => setLoadingSlots(false));
    }
  }, [open, tab, slotsData, loadingSlots, slotsEndpoint]);

  async function submitBooking() {
    setBookError("");
    if (!pickedDate || !pickedTime) { setBookError("Pick a date and time."); return; }
    if (!bookName.trim()) { setBookError("Please enter your name."); return; }
    if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(bookEmail.trim())) { setBookError("Please enter a valid email."); return; }
    setBookStage("submitting");
    try {
      const res = await fetch(bookEndpoint, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          date: pickedDate, time: pickedTime,
          visitorName: bookName.trim(), visitorEmail: bookEmail.trim(),
          tz: slotsData?.tz || "Africa/Lagos",
        }),
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok || !data.ok) {
        const errMap = {
          slot_taken: "Sorry, that slot was just booked. Please pick another.",
          slot_in_past: "That slot is in the past. Pick a future time.",
          closed_sunday: "Owner is unavailable on Sundays. Please pick another day.",
          outside_hours: "Outside owner's working hours (09:00–18:00 WAT).",
          invalid_email: "Please enter a valid email.",
          rate_limited: "Too many bookings from this IP. Try again later.",
        };
        throw new Error(errMap[data.error] || data.error || ("HTTP " + res.status));
      }
      setBookConfirmation(data);
      setBookStage("confirmed");
      // Refresh slots so the just-booked one shows taken
      fetch(slotsEndpoint).then(r => r.json()).then(setSlotsData).catch(() => {});
    } catch (e) {
      setBookError(e.message || "Could not book");
      setBookStage("error");
    }
  }

  const jitsiUrl = room
    ? `https://meet.jit.si/${room}#userInfo.displayName=%22${encodeURIComponent(visitorName || "Visitor")}%22` +
      `&config.prejoinPageEnabled=false&config.disableDeepLinking=true` +
      (video ? "" : "&config.startWithVideoMuted=true")
    : "";

  const activeDay = slotsData?.days?.find(d => d.date === pickedDate);

  return (
    <>
      {/* Floating pill */}
      <button
        type="button"
        onClick={() => { setOpen(true); setTab("now"); }}
        className="fixed bottom-6 right-6 z-[80] group flex items-center gap-3 pl-5 pr-6 py-4 rounded-full bg-gradient-to-br from-emerald-400 to-emerald-700 text-white shadow-2xl hover:scale-105 active:scale-95 transition-transform"
        style={{ boxShadow: "0 20px 60px -10px rgba(16,185,129,0.55), 0 0 0 1px rgba(255,255,255,0.08) inset" }}
        aria-label="Call owner"
      >
        <span className="relative flex h-3 w-3">
          <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-white opacity-75"></span>
          <span className="relative inline-flex rounded-full h-3 w-3 bg-white"></span>
        </span>
        <PhoneIcon className="h-5 w-5" />
        <span className="font-body font-medium tracking-wide text-sm uppercase">Call Owner</span>
      </button>

      {open && (
        <div
          className="fixed inset-0 z-[90] flex items-center justify-center bg-black/80 backdrop-blur-sm p-4"
          onClick={(e) => { if (e.target === e.currentTarget) endCall(); }}
        >
          <div className="liquid-glass-strong relative w-full max-w-2xl rounded-3xl overflow-hidden border border-white/15 max-h-[92vh] overflow-y-auto">
            {/* Header */}
            <div className="flex items-start justify-between px-6 py-5 border-b border-white/10">
              <div>
                <div className="text-[10px] tracking-[0.3em] uppercase text-white/50 font-body">Live · Direct Line</div>
                <div className="font-heading text-2xl text-white mt-1">{owner}</div>
                <div className="text-xs text-white/60 font-body">{company}</div>
              </div>
              <button onClick={endCall} className="text-white/60 hover:text-white text-2xl leading-none -mt-1" aria-label="Close">×</button>
            </div>

            {/* Tab bar — only shown in idle states */}
            {(stage === "idle" || stage === "error") && bookStage !== "confirmed" && (
              <div className="flex border-b border-white/10">
                <button
                  onClick={() => setTab("now")}
                  className={`flex-1 px-4 py-3 font-body text-xs tracking-[0.2em] uppercase transition-colors ${tab === "now" ? "text-white border-b-2 border-emerald-400 bg-white/5" : "text-white/50 hover:text-white/80"}`}
                >
                  📞 Call Now
                </button>
                <button
                  onClick={() => setTab("schedule")}
                  className={`flex-1 px-4 py-3 font-body text-xs tracking-[0.2em] uppercase transition-colors ${tab === "schedule" ? "text-white border-b-2 border-emerald-400 bg-white/5" : "text-white/50 hover:text-white/80"}`}
                >
                  📅 Schedule for Later
                </button>
              </div>
            )}

            <div className="px-6 py-6">
              {/* ===================== CALL NOW ===================== */}
              {tab === "now" && stage === "idle" && (
                <div className="space-y-5">
                  <p className="text-white/80 font-body text-sm leading-relaxed">
                    Place an instant, encrypted call to <span className="text-white font-medium">{owner}</span>. The call rings on their phone — please wait a moment for them to pick up.
                  </p>
                  <div>
                    <label className="block text-[10px] tracking-[0.3em] uppercase text-white/50 font-body mb-2">Your name (optional)</label>
                    <input
                      type="text" value={visitorName} onChange={(e) => setVisitorName(e.target.value)}
                      placeholder="e.g. Sarah from Hamburg" maxLength={80}
                      className="w-full bg-white/5 border border-white/15 rounded-2xl px-4 py-3 text-white placeholder-white/30 focus:outline-none focus:border-emerald-400 font-body"
                    />
                  </div>
                  <label className="flex items-center gap-2 cursor-pointer">
                    <input type="checkbox" checked={video} onChange={(e) => setVideo(e.target.checked)} className="accent-emerald-500" />
                    <span className="text-white/80 font-body text-sm">Start with video</span>
                  </label>
                  <button
                    onClick={startCall}
                    className="w-full flex items-center justify-center gap-3 py-4 rounded-full bg-emerald-500 hover:bg-emerald-400 text-black font-body font-semibold tracking-wide uppercase text-sm transition-colors"
                  >
                    <PhoneIcon className="h-5 w-5" /> Place the call
                  </button>
                  <p className="text-[11px] text-white/40 font-body text-center leading-relaxed">
                    Audio + HD video · End-to-end encrypted · Free for buyers worldwide
                  </p>
                </div>
              )}
              {tab === "now" && stage === "dialing" && (
                <div className="flex flex-col items-center gap-4 py-6">
                  <div className="h-16 w-16 rounded-full border-2 border-emerald-400 border-t-transparent animate-spin"></div>
                  <div className="text-white/80 font-body">Connecting to {owner}…</div>
                </div>
              )}
              {tab === "now" && stage === "ringing" && (
                <div className="flex flex-col items-center gap-4 py-6">
                  <div className="relative h-20 w-20">
                    <div className="absolute inset-0 rounded-full bg-emerald-500 animate-ping opacity-30"></div>
                    <div className="absolute inset-2 rounded-full bg-emerald-500/20 animate-pulse"></div>
                    <div className="absolute inset-0 flex items-center justify-center">
                      <PhoneIcon className="h-8 w-8 text-emerald-300" />
                    </div>
                  </div>
                  <div className="font-heading text-2xl text-white">Ringing {owner}…</div>
                  <div className="text-white/50 font-body text-sm">{ringSec}s</div>
                  <p className="text-white/60 font-body text-xs text-center max-w-md leading-relaxed">
                    A notification has been sent. The owner has been notified on their mobile device — they will join momentarily.
                  </p>
                  <button onClick={endCall} className="mt-2 text-xs uppercase tracking-[0.3em] text-white/50 hover:text-white font-body">Cancel</button>
                </div>
              )}
              {tab === "now" && stage === "connected" && (
                <div className="space-y-3">
                  <div className="aspect-video w-full rounded-2xl overflow-hidden bg-black border border-white/10">
                    <iframe title="Live call" src={jitsiUrl} allow="camera; microphone; fullscreen; display-capture; autoplay" className="w-full h-full" />
                  </div>
                  <div className="flex items-center justify-between gap-3">
                    <div className="text-xs text-white/50 font-body"><span className="text-emerald-300">●</span> Live · {ringSec}s elapsed</div>
                    <button onClick={endCall} className="px-5 py-2 rounded-full bg-red-500 hover:bg-red-400 text-white font-body text-sm uppercase tracking-wide">End call</button>
                  </div>
                </div>
              )}
              {tab === "now" && stage === "error" && (
                <div className="space-y-4">
                  <div className="text-red-300 font-body text-sm">Could not connect. {errorMsg}</div>
                  <button onClick={() => setStage("idle")} className="w-full py-3 rounded-full border border-white/20 text-white font-body uppercase tracking-wide text-sm hover:bg-white/5">Try again</button>
                </div>
              )}

              {/* ===================== SCHEDULE ===================== */}
              {tab === "schedule" && bookStage === "pick" && (
                <div className="space-y-5">
                  <p className="text-white/80 font-body text-sm leading-relaxed">
                    Book a 30-minute call with <span className="text-white font-medium">{owner}</span>. Owner's hours: <span className="text-white">Mon–Sat, 09:00–18:00 (West Africa Time)</span>.
                  </p>

                  {loadingSlots && (
                    <div className="flex items-center gap-3 text-white/60 font-body text-sm py-4">
                      <div className="h-4 w-4 rounded-full border-2 border-white/40 border-t-transparent animate-spin"></div>
                      Loading available slots…
                    </div>
                  )}

                  {!loadingSlots && slotsData?.days && (
                    <>
                      {/* Date picker — horizontal scroll */}
                      <div>
                        <label className="block text-[10px] tracking-[0.3em] uppercase text-white/50 font-body mb-2">Pick a date</label>
                        <div className="flex gap-2 overflow-x-auto pb-2" style={{ scrollbarWidth: "thin" }}>
                          {slotsData.days.map(d => (
                            <button
                              key={d.date}
                              onClick={() => { setPickedDate(d.date); setPickedTime(null); }}
                              className={`shrink-0 px-4 py-3 rounded-2xl border font-body text-xs tracking-wide transition-colors ${
                                pickedDate === d.date
                                  ? "bg-emerald-500 text-black border-emerald-400"
                                  : "bg-white/5 border-white/15 text-white/80 hover:bg-white/10"
                              }`}
                            >
                              <div className="uppercase text-[10px] tracking-[0.25em] opacity-70">{d.weekday}</div>
                              <div className="text-sm font-semibold mt-1">{d.pretty.split(", ")[1]}</div>
                            </button>
                          ))}
                        </div>
                      </div>

                      {/* Time picker — grid */}
                      {activeDay && (
                        <div>
                          <label className="block text-[10px] tracking-[0.3em] uppercase text-white/50 font-body mb-2">
                            Pick a time on {activeDay.pretty} ({slotsData.tz.split("/")[1]})
                          </label>
                          <div className="grid grid-cols-4 gap-2 max-h-48 overflow-y-auto pr-1">
                            {activeDay.slots.map(s => (
                              <button
                                key={s.time}
                                disabled={s.taken}
                                onClick={() => setPickedTime(s.time)}
                                className={`px-3 py-2 rounded-xl font-body text-sm border transition-colors ${
                                  s.taken
                                    ? "bg-white/[0.02] border-white/5 text-white/20 line-through cursor-not-allowed"
                                    : pickedTime === s.time
                                      ? "bg-emerald-500 text-black border-emerald-400"
                                      : "bg-white/5 border-white/15 text-white hover:bg-white/10"
                                }`}
                              >
                                {s.time}
                              </button>
                            ))}
                          </div>
                          {activeDay.slots.every(s => s.taken) && (
                            <p className="text-white/50 text-xs mt-2 font-body">All slots booked on this date.</p>
                          )}
                        </div>
                      )}

                      {/* Name + Email */}
                      <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                        <div>
                          <label className="block text-[10px] tracking-[0.3em] uppercase text-white/50 font-body mb-2">Your name</label>
                          <input
                            type="text" value={bookName} onChange={(e) => setBookName(e.target.value)}
                            placeholder="Full name" maxLength={80}
                            className="w-full bg-white/5 border border-white/15 rounded-2xl px-4 py-3 text-white placeholder-white/30 focus:outline-none focus:border-emerald-400 font-body"
                          />
                        </div>
                        <div>
                          <label className="block text-[10px] tracking-[0.3em] uppercase text-white/50 font-body mb-2">Your email</label>
                          <input
                            type="email" value={bookEmail} onChange={(e) => setBookEmail(e.target.value)}
                            placeholder="you@company.com" maxLength={120}
                            className="w-full bg-white/5 border border-white/15 rounded-2xl px-4 py-3 text-white placeholder-white/30 focus:outline-none focus:border-emerald-400 font-body"
                          />
                        </div>
                      </div>

                      {bookError && (
                        <div className="text-red-300 font-body text-sm">{bookError}</div>
                      )}

                      <button
                        onClick={submitBooking}
                        disabled={!pickedDate || !pickedTime || !bookName || !bookEmail}
                        className="w-full flex items-center justify-center gap-3 py-4 rounded-full bg-emerald-500 hover:bg-emerald-400 disabled:bg-white/10 disabled:text-white/30 text-black font-body font-semibold tracking-wide uppercase text-sm transition-colors"
                      >
                        📅 Confirm appointment
                        {pickedDate && pickedTime && (
                          <span className="opacity-70 font-normal normal-case ml-1">— {pickedDate.slice(5)} at {pickedTime}</span>
                        )}
                      </button>
                      <p className="text-[11px] text-white/40 font-body text-center leading-relaxed">
                        Both you and the owner will receive the meeting link.
                      </p>
                    </>
                  )}
                </div>
              )}

              {tab === "schedule" && bookStage === "submitting" && (
                <div className="flex flex-col items-center gap-4 py-8">
                  <div className="h-12 w-12 rounded-full border-2 border-emerald-400 border-t-transparent animate-spin"></div>
                  <div className="text-white/80 font-body">Booking your appointment…</div>
                </div>
              )}

              {tab === "schedule" && bookStage === "confirmed" && bookConfirmation && (
                <div className="space-y-5 py-2">
                  <div className="flex flex-col items-center gap-3 text-center">
                    <div className="h-16 w-16 rounded-full bg-emerald-500/20 flex items-center justify-center text-3xl">✓</div>
                    <div className="font-heading text-3xl text-white">Appointment booked</div>
                    <div className="text-white/70 font-body text-sm">{bookConfirmation.prettyWhen}</div>
                  </div>
                  <div className="liquid-glass p-5 rounded-2xl space-y-3">
                    <div>
                      <div className="text-[10px] tracking-[0.3em] uppercase text-white/50 font-body mb-1">Your meeting link</div>
                      <a href={bookConfirmation.joinUrl} target="_blank" rel="noopener" className="text-emerald-300 hover:text-emerald-200 font-body text-sm break-all">{bookConfirmation.joinUrl}</a>
                    </div>
                    <div className="text-xs text-white/50 font-body leading-relaxed">
                      Save this link. Open it at the scheduled time on any device — no app install required. {owner} has been notified and will join you.
                    </div>
                  </div>
                  <button onClick={endCall} className="w-full py-3 rounded-full bg-emerald-500 hover:bg-emerald-400 text-black font-body font-semibold tracking-wide uppercase text-sm">Done</button>
                </div>
              )}

              {tab === "schedule" && bookStage === "error" && (
                <div className="space-y-4">
                  <div className="text-red-300 font-body text-sm">{bookError}</div>
                  <button onClick={() => setBookStage("pick")} className="w-full py-3 rounded-full border border-white/20 text-white font-body uppercase tracking-wide text-sm hover:bg-white/5">Try again</button>
                </div>
              )}
            </div>
          </div>
        </div>
      )}
    </>
  );
}

Object.assign(window, { CallButton });
