const { useState, useEffect, useRef } = React;
const { Icon, Tick, TextBubble, PhotoCardBubble, TypingBubble, Phone, HowIllu1, HowIllu2, HowIllu3, WobblyArrow } = window.WA;

// =========================================================
// PHOTOS — one Unsplash URL per vertical (real photos in cards)
// =========================================================
const VERTICAL_PHOTOS = {
  realestate: { url: "https://images.unsplash.com/photo-1545324418-cc1a3fa10c00?w=800&auto=format&q=80", alt: "Marina apartment exterior" },
  clinic:     { url: "https://images.unsplash.com/photo-1540555700478-4be289fbecef?w=800&auto=format&q=80", alt: "Treatment room interior" },
  restaurant: { url: "https://images.unsplash.com/photo-1517248135467-4c7edcad34c4?w=800&auto=format&q=80", alt: "Plated restaurant dish" },
  fitness:    { url: "https://images.unsplash.com/photo-1534438327276-14e5300c3a48?w=800&auto=format&q=80", alt: "Fitness studio class" },
  ecom:       { url: "https://images.unsplash.com/photo-1591047139829-d91aecb6caea?w=800&auto=format&q=80", alt: "Product hero" },
};

// =========================================================
// HERO — short scripted Real Estate conversation, loops
// =========================================================
function HeroPhone() {
  const [stage, setStage] = useState(0);
  useEffect(() => {
    const timings = [1600, 1500, 1700, 1500, 1600, 1800, 2400];
    const t = setTimeout(() => setStage((s) => (s + 1) % 7), timings[stage]);
    return () => clearTimeout(t);
  }, [stage]);

  const photo = VERTICAL_PHOTOS.realestate;
  return (
    <Phone name="Sarah Chen" initials="SC" avatar="b" presence="online" size="lg">
      {stage >= 0 && <TextBubble dir="in" time="2:41 PM" delay={0} key={`a-${stage}`}>Hi! Is the 3-bed in Marina still available next weekend?</TextBubble>}
      {stage === 1 && <TypingBubble key={`ty-${stage}`} />}
      {stage >= 2 && <TextBubble dir="out" time="2:41 PM" read delay={0} key={`b-${stage}`}>Yes — Saturday 11am viewing slot is open. Here are the details:</TextBubble>}
      {stage >= 3 && <PhotoCardBubble dir="out" src={photo.url} alt={photo.alt} title="Marina View — 3BR" sub="AED 220K/yr · Saturday 11am viewing" time="2:41 PM" read delay={0} key={`c-${stage}`} />}
      {stage >= 4 && <TextBubble dir="in" time="2:42 PM" delay={0} key={`d-${stage}`}>Yes, book it</TextBubble>}
      {stage === 5 && <TypingBubble key={`ty2-${stage}`} />}
      {stage >= 6 && <TextBubble dir="out" time="2:42 PM" read delay={0} key={`e-${stage}`}>✓ Confirmed. Sending location pin + agent contact now.</TextBubble>}
    </Phone>
  );
}

// =========================================================
// INDUSTRIES (5 tabs, English-only chats, real photo cards)
// =========================================================
const INDUSTRIES = [
  {
    id: "realestate", tab: "Real Estate",
    kicker: "For brokers & property managers",
    headline: "Qualifies, schedules, and sends listings — in seconds.",
    body: "Every enquiry gets an answer in under 60 seconds. The AI pulls availability from your listing sheet, sends photos, and books the viewing — without you picking up the phone.",
    bullets: [
      { text: "Replies in under 60 seconds, 24/7" },
      { text: "Sends matching listings + photos instantly" },
      { text: "Books viewings directly into your calendar" },
    ],
    phone: { name: "Khaled A.", initials: "KA", avatar: "b", presence: "online" },
    photo: VERTICAL_PHOTOS.realestate,
    card: { title: "JVC Diamond 4 — 2BR", sub: "AED 125K/yr · 1,150 sqft" },
    chat: [
      { dir: "in",  time: "10:12", text: "Hi! Is the JVC apartment from your Property Finder listing still available?" },
      { dir: "out", time: "10:12", text: "Yes — the 2BR in Diamond 4 is available at AED 125K/yr. Want photos and a viewing?" },
      { card: true, dir: "out", time: "10:13" },
      { dir: "in",  time: "10:14", text: "Saturday 11am works" },
      { dir: "out", time: "10:14", text: "✓ Booked. I'll send the location pin and Ahmed's contact." },
    ],
  },
  {
    id: "clinic", tab: "Clinics",
    kicker: "For aesthetics & wellness",
    headline: "Books treatments and answers prep questions automatically.",
    body: "Clients ask, the AI answers — with your exact treatment descriptions, pricing, and prep instructions. Bookings drop straight into your scheduling tool.",
    bullets: [
      { text: "Sends prep instructions and aftercare info" },
      { text: "Books into Fresha, MindBody, or Google Calendar", soon: true },
      { text: "Answers pricing and treatment questions in your brand voice" },
    ],
    phone: { name: "Aisha", initials: "A", avatar: "f", presence: "online" },
    photo: VERTICAL_PHOTOS.clinic,
    card: { title: "Hydrafacial · 60 min", sub: "Fri 5:30 PM · Confirmed" },
    chat: [
      { dir: "in",  time: "4:02 PM", text: "Can I book a hydrafacial this Friday?" },
      { dir: "out", time: "4:02 PM", text: "Yes — 3pm or 5:30pm both open." },
      { dir: "in",  time: "4:03 PM", text: "5:30pm" },
      { card: true, dir: "out", time: "4:03 PM" },
      { dir: "out", time: "4:03 PM", text: "Sending prep instructions now." },
    ],
  },
  {
    id: "restaurant", tab: "Restaurants",
    kicker: "For venues & hospitality",
    headline: "Takes reservations and sends menus automatically.",
    body: "No more missed messages on Friday night. The AI takes the reservation, sends the menu, and flags allergies and dietary requirements to the kitchen.",
    bullets: [
      { text: "Books into OpenTable or SevenRooms", soon: true },
      { text: "Sends menus, directions, and parking info" },
      { text: "Flags dietary requirements to the kitchen" },
    ],
    phone: { name: "Marco R.", initials: "MR", avatar: "d", presence: "online" },
    photo: VERTICAL_PHOTOS.restaurant,
    card: { title: "Fri Nov 14 · 8:00 PM", sub: "6 guests · Vegan menu noted" },
    chat: [
      { dir: "in",  time: "7:41 PM", text: "Table for 6 Friday 8pm? One vegan in the group." },
      { dir: "out", time: "7:41 PM", text: "Got it — 8pm Friday booked." },
      { card: true, dir: "out", time: "7:41 PM" },
      { dir: "out", time: "7:42 PM", text: "Sending the menu now. See you Friday." },
    ],
  },
  {
    id: "fitness", tab: "Fitness",
    kicker: "For studios & trainers",
    headline: "Class schedules, drop-ins, and bookings — all auto.",
    body: "Members ask \"what's tomorrow?\" and get your schedule back instantly. Drop-ins, memberships, and waitlists all run on autopilot.",
    bullets: [
      { text: "Pulls live class schedule from MindBody or Glofox", soon: true },
      { text: "Handles drop-ins and converts to memberships" },
      { text: "Manages waitlists automatically" },
    ],
    phone: { name: "Priya", initials: "P", avatar: "f", presence: "online" },
    photo: VERTICAL_PHOTOS.fitness,
    card: { title: "Strength 45 · Wed 7:00 AM", sub: "Coach Mia · 2 spots left" },
    chat: [
      { dir: "in",  time: "6:18 AM", text: "What class is tomorrow at 7am?" },
      { dir: "out", time: "6:18 AM", text: "Strength 45 with Coach Mia — 2 spots left. Want me to book you in?" },
      { card: true, dir: "out", time: "6:18 AM" },
      { dir: "in",  time: "6:19 AM", text: "Yes please!" },
      { dir: "out", time: "6:19 AM", text: "Done ✓ See you at 7am." },
    ],
  },
  {
    id: "ecom", tab: "E-commerce",
    kicker: "For online stores",
    headline: "Tracking, returns, and product questions — handled.",
    body: "Answers product questions from your catalog, tracks orders, and initiates returns — all inside WhatsApp.",
    bullets: [
      { text: "Live order tracking from Shopify or WooCommerce", soon: true },
      { text: "Answers sizing, material, and stock questions" },
      { text: "Starts returns and sends labels" },
    ],
    phone: { name: "Tom K.", initials: "TK", avatar: "e", presence: "online" },
    photo: VERTICAL_PHOTOS.ecom,
    card: { title: "Order #8421 — Out for delivery", sub: "DHL DX238... · Today 2–5pm" },
    chat: [
      { dir: "in",  time: "11:04", text: "Hey where's my order #8421?" },
      { dir: "out", time: "11:04", text: "Out for delivery — ETA today 2–5pm." },
      { card: true, dir: "out", time: "11:04" },
      { dir: "in",  time: "11:05", text: "Can I change to my office address?" },
      { dir: "out", time: "11:05", text: "Yes — send the new address and I'll update the courier." },
    ],
  },
];

function Industries() {
  const [active, setActive] = useState(0);
  const cur = INDUSTRIES[active];
  const renderChat = (msg, i) => {
    if (msg.card) {
      return <PhotoCardBubble key={i} dir={msg.dir} src={cur.photo.url} alt={cur.photo.alt} title={cur.card.title} sub={cur.card.sub} time={msg.time} read delay={i * 0.25} />;
    }
    return <TextBubble key={i} dir={msg.dir} time={msg.time} read={msg.dir === "out"} delay={i * 0.25}>{msg.text}</TextBubble>;
  };
  return (
    <section id="industries">
      <div className="wrap">
        <div className="section-header">
          <span className="eyebrow">Industries</span>
          <h2 className="display">Built for businesses where every<br/><em className="italic-serif">message is revenue.</em></h2>
        </div>
        <div className="industries-tabs centered" role="tablist">
          {INDUSTRIES.map((ind, i) => (
            <button key={ind.id} role="tab" className={`industry-tab ${i === active ? "active" : ""}`} aria-selected={i === active} onClick={() => setActive(i)}>{ind.tab}</button>
          ))}
        </div>
        <div className="industry-panel" key={cur.id}>
          <div className="industry-phone-wrap">
            <Phone {...cur.phone}>{cur.chat.map(renderChat)}</Phone>
          </div>
          <div className="industry-copy">
            <span className="kicker">{cur.kicker}</span>
            <h3>{cur.headline}</h3>
            <p>{cur.body}</p>
            <ul className="industry-bullets">
              {cur.bullets.map((b, i) => (
                <li key={i}><Icon.Check /><span>{b.text}{b.soon && <span className="coming-pill">Coming Q2</span>}</span></li>
              ))}
            </ul>
          </div>
        </div>
      </div>
    </section>
  );
}

// =========================================================
// INTEGRATIONS STRIP — tiny single-line strip
// =========================================================
const STRIP_TOOLS = [
  { name: "Cal.com",        soon: false, logo: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><circle cx="9" cy="12" r="6"/><text x="16" y="15.5" fontSize="6" fill="currentColor" stroke="none" fontFamily="ui-monospace">cal</text></svg> },
  { name: "Google Calendar",soon: false, logo: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><rect x="3" y="5" width="18" height="16" rx="2"/><line x1="3" y1="10" x2="21" y2="10"/><line x1="8" y1="3" x2="8" y2="7"/><line x1="16" y1="3" x2="16" y2="7"/><circle cx="12" cy="15" r="2.5"/></svg> },
  { name: "Outlook",        soon: false, logo: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><rect x="2" y="6" width="13" height="13" rx="2"/><path d="M15 10 L22 7 V18 L15 15"/><circle cx="8.5" cy="12.5" r="2.5"/></svg> },
  { name: "Fresha",         soon: true,  logo: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"><path d="M5 5 V19 M5 5 H13 M5 11 H11"/><circle cx="18" cy="14" r="3"/></svg> },
  { name: "OpenTable",      soon: true,  logo: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><circle cx="12" cy="12" r="8"/><ellipse cx="12" cy="12" rx="3" ry="8"/><line x1="4" y1="12" x2="20" y2="12"/></svg> },
  { name: "Mindbody",       soon: true,  logo: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"><path d="M12 4 C7 7 7 12 12 12 C17 12 17 7 12 4z"/><path d="M12 12 C7 15 7 20 12 20 C17 20 17 15 12 12z"/></svg> },
  { name: "Shopify",        soon: true,  logo: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinejoin="round"><path d="M9 5 C7 5 6 7 6 9 L4 19 L17 21 L19 9 C19 7 17 5 15 5z"/><path d="M11 9 C11 7 12 4 14 4"/></svg> },
];

function IntegrationsStrip() {
  return (
    <div className="integrations-strip-wrap reveal">
      <div className="integrations-strip">
        <span className="strip-label">Connects with</span>
        {STRIP_TOOLS.map((tool) => (
          <span key={tool.name} className="int-mini">
            <span className="int-mini-logo">{tool.logo}</span>
            <span className="int-mini-tip">{tool.name}{tool.soon && <span className="soon">· Coming Q2</span>}</span>
          </span>
        ))}
        <span className="strip-more">+ on request</span>
      </div>
    </div>
  );
}

// =========================================================
// TRY IT YOURSELF — interactive demo using window.claude.complete
// =========================================================
const DEMO_VERTICALS = [
  {
    id: "realestate", label: "Real Estate",
    persona: "Marina Real Estate (Dubai)", initials: "MR",
    placeholder: "Ask about an apartment, viewing, price…",
    suggestions: ["Is the 2BR in Marina available?", "Can I view this weekend?", "What's the price range?"],
    cardKeywords: ["apartment", "property", "flat", "bedroom", "bhk", "viewing", "marina", "villa", "townhouse", "rent", "buy", "see it", "show me"],
    cardTemplate: { title: "Marina View — 2BR Apartment", sub: "AED 165K/yr · Available now" },
  },
  {
    id: "clinic", label: "Clinic",
    persona: "Glow Aesthetics Clinic", initials: "GA",
    placeholder: "Ask about a treatment, booking, prep…",
    suggestions: ["Book a hydrafacial Friday", "How much is botox?", "What should I do before the appointment?"],
    cardKeywords: ["book", "appointment", "treatment", "facial", "botox", "filler", "schedule", "slot", "friday", "saturday", "tomorrow"],
    cardTemplate: { title: "Hydrafacial · 60 min", sub: "Fri 5:30 PM · Confirmed" },
  },
  {
    id: "restaurant", label: "Restaurant",
    persona: "Olive & Vine Restaurant", initials: "OV",
    placeholder: "Reserve a table, ask about the menu…",
    suggestions: ["Table for 4 tonight 8pm", "Do you have vegan options?", "What time do you close?"],
    cardKeywords: ["table", "reserve", "reservation", "book", "tonight", "dinner", "lunch", "menu", "guests"],
    cardTemplate: { title: "Reservation Confirmed", sub: "Tonight · 8:00 PM · 4 guests" },
  },
  {
    id: "fitness", label: "Fitness",
    persona: "Pulse Studio", initials: "PS",
    placeholder: "Ask about classes, schedule, booking…",
    suggestions: ["What class is at 7am tomorrow?", "Do you do drop-ins?", "Book me into yoga Saturday"],
    cardKeywords: ["class", "book", "yoga", "spin", "strength", "tomorrow", "drop", "session", "workout"],
    cardTemplate: { title: "Strength 45 · Wed 7:00 AM", sub: "Coach Mia · 2 spots left" },
  },
  {
    id: "ecom", label: "E-commerce",
    persona: "Linen & Co.", initials: "LC",
    placeholder: "Track an order, ask about a product…",
    suggestions: ["Where's my order #8421?", "What sizes do you have?", "How do I return something?"],
    cardKeywords: ["order", "tracking", "track", "delivery", "where", "shipped", "package", "return", "refund"],
    cardTemplate: { title: "Order #8421 — Out for delivery", sub: "DHL DX238... · Today 2–5pm" },
  },
];

const SCRIPTED_FALLBACK = {
  realestate: "Yes — that one's available. Want me to send photos and a viewing slot?",
  clinic: "Sure — I have Friday 3pm or 5:30pm open. Which works?",
  restaurant: "Got it. Booking your table now — confirming back in a sec.",
  fitness: "Yes! That class still has spots. Want me to book you in?",
  ecom: "On it — let me pull that up for you right now.",
};

function TryItPhone({ verticalId }) {
  const vertical = DEMO_VERTICALS.find((v) => v.id === verticalId);
  const photo = VERTICAL_PHOTOS[verticalId];
  const [messages, setMessages] = useState([]);
  const [typing, setTyping] = useState(false);
  const [input, setInput] = useState("");
  const [sending, setSending] = useState(false);
  const [showCaption, setShowCaption] = useState(false);
  const bodyRef = useRef(null);
  const idleTimerRef = useRef(null);

  // Reset on vertical change
  useEffect(() => {
    setMessages([{ dir: "out", text: `Hi 👋 — this is ${vertical.persona}. How can I help?`, time: nowTime() }]);
    setTyping(false);
    setShowCaption(false);
  }, [verticalId]);

  // Auto-scroll to bottom
  useEffect(() => {
    if (bodyRef.current) bodyRef.current.scrollTop = bodyRef.current.scrollHeight;
  }, [messages, typing]);

  function nowTime() {
    const d = new Date();
    return d.toLocaleTimeString([], { hour: "numeric", minute: "2-digit" });
  }

  async function handleSend(rawText) {
    const text = (rawText ?? input).trim();
    if (!text || sending) return;
    setInput("");
    setSending(true);
    setShowCaption(false);
    if (idleTimerRef.current) clearTimeout(idleTimerRef.current);

    // Add user msg
    setMessages((m) => [...m, { dir: "in", text, time: nowTime() }]);

    // Typing indicator after a tick
    await new Promise((r) => setTimeout(r, 350));
    setTyping(true);

    let reply = "";
    let triggerCard = false;
    try {
      // Build full conversation history for context
      const history = [...messages, { dir: "in", text }]
        .filter((m) => m.text && !m.card)
        .map((m) => ({ role: m.dir === "in" ? "user" : "assistant", content: m.text }));

      const apiResp = await fetch("/api/chat", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ vertical: verticalId, messages: history }),
      });

      if (apiResp.ok) {
        const data = await apiResp.json();
        const raw = (data && data.reply) || "";
        if (typeof raw === "string" && raw.length > 0) {
          if (/\[SEND_CARD\]/i.test(raw)) {
            triggerCard = true;
            reply = raw.replace(/\[SEND_CARD\]/gi, "").trim();
          } else {
            reply = raw.trim();
          }
        }
      }
    } catch (e) {
      // fall through to scripted fallback
    }

    if (!reply) {
      reply = SCRIPTED_FALLBACK[verticalId];
      const lc = text.toLowerCase();
      triggerCard = vertical.cardKeywords.some((k) => lc.includes(k));
    }

    // Show typing for ~1.2s minimum
    await new Promise((r) => setTimeout(r, 800));
    setTyping(false);
    setMessages((m) => [...m, { dir: "out", text: reply, time: nowTime() }]);

    if (triggerCard) {
      await new Promise((r) => setTimeout(r, 500));
      setMessages((m) => [...m, { card: true, dir: "out", time: nowTime() }]);
    }

    setSending(false);

    // Idle caption
    idleTimerRef.current = setTimeout(() => setShowCaption(true), 2000);
  }

  return (
    <>
      <div className="tryit-phone-host">
        <div className="phone tryit-phone">
          <div className="phone-notch"/>
          <div className="phone-screen">
            <div className="wa-header">
              <div className="wa-back"><Icon.Back /></div>
              <div className="wa-avatar">{vertical.initials}</div>
              <div>
                <div className="wa-name">{vertical.persona}</div>
                <div className="wa-presence">{typing ? "typing…" : "online"}</div>
              </div>
              <div className="wa-head-actions"><Icon.Video /><Icon.Phone /><Icon.More /></div>
            </div>
            <div className="wa-body" ref={bodyRef}>
              <div className="wa-date">TODAY</div>
              {messages.map((m, i) => {
                if (m.card) {
                  return <PhotoCardBubble key={i} dir={m.dir} src={photo.url} alt={photo.alt} title={vertical.cardTemplate.title} sub={vertical.cardTemplate.sub} time={m.time} read/>;
                }
                return <TextBubble key={i} dir={m.dir} time={m.time} read={m.dir === "out"}>{m.text}</TextBubble>;
              })}
              {typing && <TypingBubble />}
            </div>
            <form className="wa-input-live" onSubmit={(e) => { e.preventDefault(); handleSend(); }}>
              <button type="button" className="icon-btn" tabIndex="-1"><Icon.Emoji /></button>
              <input
                className="field-input"
                value={input}
                onChange={(e) => setInput(e.target.value)}
                placeholder={vertical.placeholder}
                disabled={sending}
              />
              <button type="submit" className="send-live" disabled={sending || !input.trim()} aria-label="Send">
                <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="M3 12 L21 4 L13 21 L11 13 Z"/></svg>
              </button>
            </form>
          </div>
        </div>
      </div>
      <div className="tryit-suggestions">
        {vertical.suggestions.map((s, i) => (
          <button key={i} className="tryit-sugg" onClick={() => handleSend(s)} disabled={sending}>{s}</button>
        ))}
      </div>
      <div className={`tryit-caption ${showCaption ? "show" : ""}`}>
        Live AI generation — your customers get the same speed and quality on their <span className="em">WhatsApp</span>.
      </div>
    </>
  );
}

function TryIt() {
  const [verticalId, setVerticalId] = useState("realestate");
  return (
    <section id="tryit">
      <div className="wrap-narrow">
        <div className="section-header" style={{ textAlign: "center", margin: "0 auto clamp(40px, 5vw, 64px)" }}>
          <span className="eyebrow" style={{ justifyContent: "center" }}>Try it</span>
          <h2 className="display" style={{ marginTop: 16 }}>Type anything.<br/><em className="italic-serif">Watch it work.</em></h2>
          <p className="lede" style={{ margin: "20px auto 0" }}>Same engine that runs in your customers' WhatsApp. Embedded here so you can feel it before you book a demo.</p>
        </div>
        <div className="tryit-stage">
          <div className="tryit-vertical-pills" role="tablist">
            {DEMO_VERTICALS.map((v) => (
              <button key={v.id} role="tab" aria-selected={v.id === verticalId} className={`tryit-pill ${v.id === verticalId ? "active" : ""}`} onClick={() => setVerticalId(v.id)}>{v.label}</button>
            ))}
          </div>
          <TryItPhone verticalId={verticalId} key={verticalId}/>
        </div>
      </div>
    </section>
  );
}

// =========================================================
// FAQ
// =========================================================
const FAQS = [
  { q: "How long does setup take?", a: "48 hours from sign-up to live. All we need from you: your WhatsApp Business number, your product or service catalog, and 10–20 sample messages from your inbox so the AI matches your tone. We handle the platform setup end-to-end on your behalf." },
  { q: "Which WhatsApp setup do I need?", a: "Works with any WhatsApp Business number. We handle the platform setup end-to-end and cover platform fees as part of your monthly bill. You don't need a new number." },
  { q: "Will my customers know it's AI?", a: "That's your call. Most clients prefer to disclose after a booking is confirmed. Customers care about speed and accuracy, not whether a human typed it." },
  { q: "What if the AI gets a question wrong?", a: "It's conservative by default — if it's uncertain, it asks clarifying questions or escalates to you instantly. You see every conversation in real time and can intervene mid-thread." },
  { q: "Can I see every conversation it has?", a: "All of them. Live, searchable, exportable. You can step into any conversation at any time." },
  { q: "Can I cancel anytime?", a: "Yes. Month-to-month, cancel with 7 days' notice. 14-day money-back on your first month if it's not for you." },
];

function FAQ() {
  const [open, setOpen] = useState(0);
  return (
    <div className="faq-list">
      {FAQS.map((f, i) => (
        <div key={i} className={`faq-item ${open === i ? "open" : ""}`}>
          <button className="faq-q" onClick={() => setOpen(open === i ? -1 : i)}>
            <span>{f.q}</span>
            <span className="faq-icon" aria-hidden="true"/>
          </button>
          <div className="faq-a"><div className="faq-a-inner">{f.a}</div></div>
        </div>
      ))}
    </div>
  );
}

// =========================================================
// APP
// =========================================================
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "showIndustries": true,
  "showHow": true,
  "showTryIt": true,
  "showPricing": true,
  "showFAQLink": true,
  "showFinalCTA": true
}/*EDITMODE-END*/;

function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [scrolled, setScrolled] = useState(false);
  const progressRef = useRef(null);

  useEffect(() => {
    document.documentElement.setAttribute("data-theme", "dark");
    try { localStorage.removeItem("wa-theme"); } catch (e) {}
  }, []);

  useEffect(() => {
    const onScroll = () => {
      setScrolled(window.scrollY > 20);
      const h = document.documentElement.scrollHeight - window.innerHeight;
      const r = h > 0 ? window.scrollY / h : 0;
      if (progressRef.current) progressRef.current.style.transform = `scaleX(${r})`;
    };
    window.addEventListener("scroll", onScroll);
    onScroll();
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  useEffect(() => {
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => { if (e.isIntersecting) e.target.classList.add("in"); });
    }, { threshold: 0.12, rootMargin: "-40px" });
    document.querySelectorAll(".reveal, .reveal-stagger").forEach((el) => io.observe(el));
    return () => io.disconnect();
  }, []);

  return (
    <>
      <div ref={progressRef} className="scroll-progress" style={{ transform: "scaleX(0)" }}/>
      <nav className={`nav ${scrolled ? "scrolled" : ""}`}>
        <a href="#" className="nav-logo" aria-label="SamaLabs home">
          <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 556 531" fill="var(--emerald)" fillRule="evenodd" style={{ height: 36, width: "auto", display: "block" }}>
            <path d="M234.59,503.35C236.96,499.36 243.72,488.22 249.62,478.60C266.87,450.43 299.88,395.81 305.16,386.72L310.02,378.35L307.46,376.22C302.26,371.91 266.05,341.25 264.69,340.00C263.50,338.91 264.97,335.76 274.35,319.40C325.65,229.89 338.52,207.34 338.90,206.30C339.47,204.69 339.46,204.67 345.81,216.10C348.86,221.60 361.69,244.33 374.31,266.60C386.93,288.87 402.35,316.10 408.58,327.10C441.99,386.12 483.51,459.34 488.54,468.10C491.70,473.60 495.74,480.69 497.51,483.85L500.75,489.60L476.42,489.55L452.10,489.51L434.15,457.83C424.28,440.41 403.61,404.32 388.21,377.63C372.82,350.94 357.94,325.10 355.16,320.21C352.38,315.31 349.65,311.43 349.10,311.57C347.37,312.03 338.71,333.94 339.60,335.60C340.05,336.42 347.03,348.58 355.11,362.60C379.26,404.48 415.48,467.69 428.03,489.85L439.78,510.60L487.69,510.60C515.01,510.60 535.60,510.22 535.60,509.71C535.60,508.10 523.32,486.25 418.61,301.60C391.38,253.57 353.60,186.85 345.08,171.74L339.81,162.39L337.31,166.74C335.93,169.14 330.77,178.30 325.83,187.10C320.90,195.90 308.18,218.17 297.58,236.60C286.98,255.03 271.36,282.25 262.87,297.10C254.38,311.95 247.26,324.27 247.05,324.48C246.72,324.81 237.44,317.15 191.67,278.71C184.20,272.44 178.18,267.04 178.28,266.71C178.38,266.37 188.22,248.33 200.15,226.60C232.31,168.03 264.69,107.63 284.84,68.60C289.53,59.52 297.02,45.01 301.50,36.35C305.97,27.69 309.38,20.60 309.08,20.60C304.86,20.60 226.07,66.34 120.10,130.30C93.70,146.24 64.45,163.90 55.10,169.54C45.75,175.18 37.54,180.26 36.85,180.82C35.89,181.61 35.60,191.18 35.60,222.47L35.60,263.10L76.76,296.60C99.40,315.03 118.34,330.78 118.86,331.61C119.54,332.73 116.03,339.75 105.35,358.61C61.89,435.36 20.60,509.14 20.60,510.04C20.60,510.35 67.78,510.60 125.44,510.60L230.29,510.60L234.59,503.35ZM56.60,488.82C56.60,488.40 64.97,473.21 75.20,455.07C85.44,436.94 97.72,415.12 102.50,406.60C107.27,398.08 116.79,381.10 123.64,368.87C130.49,356.64 136.33,346.63 136.61,346.62C136.89,346.61 140.50,349.41 144.63,352.85C148.77,356.29 162.49,367.69 175.12,378.19C187.76,388.68 198.71,398.01 199.45,398.91C200.62,400.33 200.12,401.83 195.72,410.07L190.64,419.58L193.02,429.66C194.33,435.20 195.60,439.93 195.85,440.18C196.50,440.83 224.60,395.06 224.60,393.35C224.60,392.56 222.15,389.93 219.16,387.50C216.17,385.08 188.14,361.72 156.87,335.60C125.60,309.48 90.49,280.45 78.85,271.10L57.68,254.10L57.64,223.46L57.60,192.81L88.85,173.86C176.25,120.87 257.71,72.38 258.31,72.98C258.98,73.65 224.54,138.07 177.65,223.84L161.40,253.57L154.75,247.77C151.09,244.58 144.53,238.96 140.18,235.28L132.25,228.60L123.68,228.61C118.96,228.61 112.00,228.91 108.21,229.27L101.31,229.92L104.34,232.51C126.39,251.39 170.08,288.30 217.11,327.75C249.00,354.51 276.84,377.93 278.98,379.78L282.85,383.16L276.64,393.63C273.22,399.39 258.71,423.34 244.39,446.85L218.35,489.60L137.48,489.60C92.99,489.60 56.60,489.25 56.60,488.82Z"/>
          </svg>
          <span style={{ fontSize: 17, letterSpacing: "-0.01em", color: "var(--ink)", fontFamily: "Inter, sans-serif" }}>
            <span style={{ fontWeight: 500 }}>Sama</span><span style={{ fontWeight: 700 }}>Labs</span>
          </span>
        </a>
        <div className="nav-links">
          <a href="#industries">Industries</a>
          <a href="#how">How it works</a>
          <a href="#tryit">Try it</a>
          <a href="FAQ.html">FAQ</a>
          <a href="#pricing">Pricing</a>
          <a className="btn btn-primary" href="#cta">Book a demo</a>
        </div>
      </nav>

      {/* 1 — HERO */}
      <section className="hero">
        <div className="hero-mesh" aria-hidden="true"/>
        <div className="hero-inner wrap">
          <span className="eyebrow hero-eyebrow">AI for WhatsApp Business</span>
          <h1 className="display">
            Never leave a WhatsApp <em className="italic-serif" style={{ color: "var(--emerald-2)" }}>unanswered again.</em>
          </h1>
          <p className="hero-sub">
            AI that <span className="em">replies, qualifies, and books</span> — in any language, on any WhatsApp Business number. 24/7.
          </p>
          <div className="hero-ctas">
            <a className="btn btn-primary btn-lg" href="#cta">Book a 15-min demo</a>
            <a className="btn btn-ghost btn-lg" href="#tryit">Try it below</a>
          </div>
        </div>
      </section>

      {/* 2 — INDUSTRIES */}
      {t.showIndustries && <Industries />}

      {/* 3 — HOW IT WORKS */}
      {t.showHow && <section id="how">
        <div className="wrap">
          <div className="section-header reveal">
            <span className="eyebrow">How it works</span>
            <h2 className="display">Three steps. <em className="italic-serif">Live in 48 hours.</em></h2>
          </div>
          <div className="how-grid reveal-stagger">
            <div className="how-col">
              <span className="num">STEP 01</span>
              <div className="how-illu"><HowIllu1 /></div>
              <div className="t">Connect your WhatsApp.</div>
              <div className="b">We connect to your existing WhatsApp Business number. No new number, no channel switch.</div>
            </div>
            <div className="how-arrow"><WobblyArrow /></div>
            <div className="how-col">
              <span className="num">STEP 02</span>
              <div className="how-illu"><HowIllu2 /></div>
              <div className="t">We configure your AI.</div>
              <div className="b">Send us your listings, menu, or services. We build your custom AI in 48 hours.</div>
            </div>
            <div className="how-arrow"><WobblyArrow /></div>
            <div className="how-col">
              <span className="num">STEP 03</span>
              <div className="how-illu"><HowIllu3 /></div>
              <div className="t">Every message answered.</div>
              <div className="b">Your AI handles every inquiry instantly. You handle the deals worth your personal time.</div>
            </div>
          </div>
          <IntegrationsStrip />
        </div>
      </section>}

      {/* 4 — TRY IT YOURSELF */}
      {t.showTryIt && <TryIt />}

      {/* 5 — PRICING */}
      {t.showPricing && <section id="pricing">
        <div className="wrap">
          <div className="section-header reveal">
            <span className="eyebrow">Pricing</span>
            <h2 className="display">Pay for the conversations<br/>you <em className="italic-serif">actually use.</em></h2>
          </div>
          <div className="pricing-grid reveal-stagger">
            <div className="price-card">
              <div className="price-name">Starter</div>
              <div className="price-amt"><span className="num">AED 499</span><span className="per">/mo</span></div>
              <div className="price-setup">+ AED 1,800 setup (one-time)</div>
              <p className="price-desc">For solo operators getting replies off their plate.</p>
              <ul className="price-features">
                <li><Icon.Check /><span>200 conversations/mo · text replies + qualification</span></li>
                <li><Icon.Check /><span>Calendar integration (Cal.com, Google, Outlook)</span></li>
                <li><Icon.Check /><span>Email support</span></li>
                <li><Icon.Check /><span>AED 1.50/conv beyond included</span></li>
              </ul>
              <div className="price-cta"><a className="btn btn-ghost" href="#cta">Start</a></div>
            </div>
            <div className="price-card pro">
              <span className="tag-popular">Most popular</span>
              <div className="price-name">Pro</div>
              <div className="price-amt"><span className="num">AED 999</span><span className="per">/mo</span></div>
              <div className="price-setup">+ AED 3,000 setup (one-time)</div>
              <p className="price-desc">For businesses where every message is revenue.</p>
              <ul className="price-features">
                <li><Icon.Check /><span>1,000 conversations/mo · everything in Starter</span></li>
                <li><Icon.Check /><span>Booking integrations (Fresha, OpenTable)<span className="coming-pill">Coming Q2</span></span></li>
                <li><Icon.Check /><span>Hot-lead detection + escalation</span></li>
                <li><Icon.Check /><span>Priority support</span></li>
                <li><Icon.Check /><span>AED 1.25/conv beyond included</span></li>
              </ul>
              <div className="price-cta"><a className="btn btn-primary" href="#cta">Book a demo</a></div>
            </div>
            <div className="price-card elite">
              <div className="price-name">Custom</div>
              <div className="price-amt"><span className="num">Talk to us</span></div>
              <div className="price-setup">Built for your scale</div>
              <p className="price-desc">For brokerages with 100+ agents, multi-location chains, white-label needs, or high-volume verticals.</p>
              <ul className="price-features">
                <li><Icon.Check /><span>Unlimited conversations · everything in Pro</span></li>
                <li><Icon.Check /><span>Multi-tenant + multi-location config</span></li>
                <li><Icon.Check /><span>Custom knowledge base + integrations</span></li>
                <li><Icon.Check /><span>White-label options</span></li>
                <li><Icon.Check /><span>Dedicated success manager + SLA</span></li>
                <li><Icon.Check /><span>Volume pricing on conversations</span></li>
              </ul>
              <div className="price-cta"><a className="btn btn-ghost" href="#cta">Book a strategy call</a></div>
            </div>
          </div>
          <p className="pricing-fineprint">Month-to-month. 14-day money-back on month 1. Annual prepay: 15% off.</p>
        </div>
      </section>}

      {/* 6 — FAQ link callout */}
      {t.showFAQLink && <section id="faq-link" style={{ paddingTop: "60px", paddingBottom: "60px" }}>
        <div className="wrap-narrow" style={{ textAlign: "center" }}>
          <a href="FAQ.html" className="faq-link-card">
            <div>
              <span className="eyebrow" style={{ justifyContent: "center", marginBottom: 12 }}>Have questions?</span>
              <span className="faq-link-title">Read the FAQ <span className="arrow">→</span></span>
            </div>
          </a>
        </div>
      </section>}

      {/* 7 — FINAL CTA */}
      {t.showFinalCTA && <section id="cta" className="final">
        <div className="wrap-narrow">
          <h2 className="display">Your next lead is sending<br/>a WhatsApp <em className="italic-serif">right now.</em></h2>
          <p>Be the business that replies in 60 seconds — while you're busy with the last one.</p>
          <a className="btn btn-primary btn-xl" href="https://cal.com/samalabs-rbrmuq/samalabs-demo">Book a 15-min demo</a>
        </div>
      </section>}

      {/* FOOTER */}
      <footer className="footer">
        <div className="wrap">
          <div className="footer-inner">
            <div style={{ display: "flex", gap: 12, alignItems: "center" }}>
              <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 556 531" fill="var(--emerald)" fillRule="evenodd" style={{ height: 24, width: "auto", display: "block" }}>
                <path d="M234.59,503.35C236.96,499.36 243.72,488.22 249.62,478.60C266.87,450.43 299.88,395.81 305.16,386.72L310.02,378.35L307.46,376.22C302.26,371.91 266.05,341.25 264.69,340.00C263.50,338.91 264.97,335.76 274.35,319.40C325.65,229.89 338.52,207.34 338.90,206.30C339.47,204.69 339.46,204.67 345.81,216.10C348.86,221.60 361.69,244.33 374.31,266.60C386.93,288.87 402.35,316.10 408.58,327.10C441.99,386.12 483.51,459.34 488.54,468.10C491.70,473.60 495.74,480.69 497.51,483.85L500.75,489.60L476.42,489.55L452.10,489.51L434.15,457.83C424.28,440.41 403.61,404.32 388.21,377.63C372.82,350.94 357.94,325.10 355.16,320.21C352.38,315.31 349.65,311.43 349.10,311.57C347.37,312.03 338.71,333.94 339.60,335.60C340.05,336.42 347.03,348.58 355.11,362.60C379.26,404.48 415.48,467.69 428.03,489.85L439.78,510.60L487.69,510.60C515.01,510.60 535.60,510.22 535.60,509.71C535.60,508.10 523.32,486.25 418.61,301.60C391.38,253.57 353.60,186.85 345.08,171.74L339.81,162.39L337.31,166.74C335.93,169.14 330.77,178.30 325.83,187.10C320.90,195.90 308.18,218.17 297.58,236.60C286.98,255.03 271.36,282.25 262.87,297.10C254.38,311.95 247.26,324.27 247.05,324.48C246.72,324.81 237.44,317.15 191.67,278.71C184.20,272.44 178.18,267.04 178.28,266.71C178.38,266.37 188.22,248.33 200.15,226.60C232.31,168.03 264.69,107.63 284.84,68.60C289.53,59.52 297.02,45.01 301.50,36.35C305.97,27.69 309.38,20.60 309.08,20.60C304.86,20.60 226.07,66.34 120.10,130.30C93.70,146.24 64.45,163.90 55.10,169.54C45.75,175.18 37.54,180.26 36.85,180.82C35.89,181.61 35.60,191.18 35.60,222.47L35.60,263.10L76.76,296.60C99.40,315.03 118.34,330.78 118.86,331.61C119.54,332.73 116.03,339.75 105.35,358.61C61.89,435.36 20.60,509.14 20.60,510.04C20.60,510.35 67.78,510.60 125.44,510.60L230.29,510.60L234.59,503.35ZM56.60,488.82C56.60,488.40 64.97,473.21 75.20,455.07C85.44,436.94 97.72,415.12 102.50,406.60C107.27,398.08 116.79,381.10 123.64,368.87C130.49,356.64 136.33,346.63 136.61,346.62C136.89,346.61 140.50,349.41 144.63,352.85C148.77,356.29 162.49,367.69 175.12,378.19C187.76,388.68 198.71,398.01 199.45,398.91C200.62,400.33 200.12,401.83 195.72,410.07L190.64,419.58L193.02,429.66C194.33,435.20 195.60,439.93 195.85,440.18C196.50,440.83 224.60,395.06 224.60,393.35C224.60,392.56 222.15,389.93 219.16,387.50C216.17,385.08 188.14,361.72 156.87,335.60C125.60,309.48 90.49,280.45 78.85,271.10L57.68,254.10L57.64,223.46L57.60,192.81L88.85,173.86C176.25,120.87 257.71,72.38 258.31,72.98C258.98,73.65 224.54,138.07 177.65,223.84L161.40,253.57L154.75,247.77C151.09,244.58 144.53,238.96 140.18,235.28L132.25,228.60L123.68,228.61C118.96,228.61 112.00,228.91 108.21,229.27L101.31,229.92L104.34,232.51C126.39,251.39 170.08,288.30 217.11,327.75C249.00,354.51 276.84,377.93 278.98,379.78L282.85,383.16L276.64,393.63C273.22,399.39 258.71,423.34 244.39,446.85L218.35,489.60L137.48,489.60C92.99,489.60 56.60,489.25 56.60,488.82Z"/>
              </svg>
              <span style={{ fontSize: 14, letterSpacing: "-0.01em", color: "var(--ink)", fontFamily: "Inter, sans-serif" }}>
                <span style={{ fontWeight: 500 }}>Sama</span><span style={{ fontWeight: 700 }}>Labs</span>
              </span>
              <span className="tagline" style={{ marginLeft: 6 }}>· AI for WhatsApp Business</span>
            </div>
            <div style={{ display: "flex", gap: 24, alignItems: "center", flexWrap: "wrap" }}>
              <a href="mailto:hello@samalabs.ai">hello@samalabs.ai</a>
              <a href="#cta">Book a demo</a>
              <span className="copy">© 2026</span>
            </div>
          </div>
        </div>
      </footer>

      <TweaksPanel title="Tweaks · Page sections">
        <TweakSection label="Sections" />
        <TweakToggle label="Industries"            value={t.showIndustries} onChange={(v) => setTweak('showIndustries', v)} />
        <TweakToggle label="How it works"          value={t.showHow}        onChange={(v) => setTweak('showHow', v)} />
        <TweakToggle label="Try it yourself"       value={t.showTryIt}      onChange={(v) => setTweak('showTryIt', v)} />
        <TweakToggle label="Pricing"               value={t.showPricing}    onChange={(v) => setTweak('showPricing', v)} />
        <TweakToggle label="FAQ link callout"     value={t.showFAQLink}    onChange={(v) => setTweak('showFAQLink', v)} />
        <TweakToggle label="Final CTA"             value={t.showFinalCTA}   onChange={(v) => setTweak('showFinalCTA', v)} />
      </TweaksPanel>
    </>
  );
}

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