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

/* ----------------------------------------------------------
   Small presentational bits
---------------------------------------------------------- */
function Tick({ size = 13, color = "#fff" }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" aria-hidden="true">
      <path d="M20 6L9 17l-5-5" stroke={color} strokeWidth="3.2" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );
}
function Stars({ n = 5 }) {
  return (
    <span style={{ color: "#E0962A", fontSize: 12, letterSpacing: "1px" }}>
      {"★".repeat(n)}
    </span>
  );
}

/* Verdict card shown inside Adam's bubble */
function VerdictCard({ status, name, sub, meta }) {
  const map = {
    halal:   { bg: "var(--halal-bg)",   fg: "var(--halal)",   label: "HALAL",   icon: "✓" },
    haram:   { bg: "var(--haram-bg)",   fg: "var(--haram)",   label: "HARAM",   icon: "✕" },
    unclear: { bg: "var(--unclear-bg)", fg: "var(--unclear)", label: "UNCLEAR", icon: "!" },
  };
  const c = map[status];
  return (
    <div style={{ borderRadius: 14, overflow: "hidden", border: "1px solid var(--line)", background: "#fff", minWidth: 222 }}>
      <div style={{ background: c.bg, padding: "10px 12px", display: "flex", alignItems: "center", gap: 9 }}>
        <span style={{
          width: 26, height: 26, borderRadius: "50%", background: c.fg, color: "#fff",
          display: "grid", placeItems: "center", fontWeight: 900, fontSize: 15, flexShrink: 0,
        }}>{c.icon}</span>
        <span style={{ fontWeight: 900, color: c.fg, fontSize: 15, letterSpacing: ".04em" }}>{c.label}</span>
      </div>
      <div style={{ padding: "10px 12px 12px" }}>
        <div style={{ fontWeight: 800, fontSize: 14.5, color: "var(--ink)" }}>{name}</div>
        <div style={{ fontSize: 12.5, color: "var(--ink-soft)", marginTop: 2, lineHeight: 1.35 }}>{sub}</div>
        {meta && (
          <div style={{ marginTop: 8, fontSize: 11.5, color: "var(--ink-faint)", display: "flex", alignItems: "center", gap: 6 }}>
            <span style={{ width: 14, height: 14, borderRadius: 4, background: "var(--gold)", color: "#fff", display: "grid", placeItems: "center", fontSize: 9, fontWeight: 900 }}>H</span>
            {meta}
          </div>
        )}
      </div>
    </div>
  );
}

function RestaurantCard() {
  const rows = [
    { name: "Karahi Boys", cui: "Pakistani · Shawarma", d: "1.2 km", n: 5 },
    { name: "Iqbal Halal Foods", cui: "Desi · Grill", d: "2.0 km", n: 4 },
  ];
  return (
    <div style={{ borderRadius: 14, overflow: "hidden", border: "1px solid var(--line)", background: "#fff", minWidth: 232 }}>
      <div style={{ padding: "9px 12px", borderBottom: "1px solid var(--line-soft)", fontWeight: 800, fontSize: 13, color: "var(--wa-deep)" }}>
        🍽️ 3 halal spots near you
      </div>
      {rows.map((r, i) => (
        <div key={i} style={{ display: "flex", gap: 10, padding: "9px 12px", borderBottom: i < rows.length - 1 ? "1px solid var(--line-soft)" : "none", alignItems: "center" }}>
          <div style={{ width: 36, height: 36, borderRadius: 9, background: "linear-gradient(135deg,#DDF6D6,#BFE9C5)", flexShrink: 0, display: "grid", placeItems: "center", fontSize: 16 }}>🌯</div>
          <div style={{ minWidth: 0, flex: 1 }}>
            <div style={{ fontWeight: 800, fontSize: 13.5, color: "var(--ink)" }}>{r.name}</div>
            <div style={{ fontSize: 11.5, color: "var(--ink-soft)" }}>{r.cui}</div>
          </div>
          <div style={{ textAlign: "right", flexShrink: 0 }}>
            <Stars n={r.n} />
            <div style={{ fontSize: 11, color: "var(--ink-faint)", fontWeight: 700 }}>{r.d}</div>
          </div>
        </div>
      ))}
    </div>
  );
}

function PriceCard() {
  const rows = [
    { store: "No Frills", price: "$3.49/lb", best: true },
    { store: "FreshCo", price: "$3.99/lb", best: false },
    { store: "Walmart", price: "$4.27/lb", best: false },
  ];
  return (
    <div style={{ borderRadius: 14, overflow: "hidden", border: "1px solid var(--line)", background: "#fff", minWidth: 230 }}>
      <div style={{ padding: "9px 12px", borderBottom: "1px solid var(--line-soft)", fontWeight: 800, fontSize: 13, color: "var(--wa-deep)" }}>
        💰 Halal chicken thighs · this week
      </div>
      {rows.map((r, i) => (
        <div key={i} style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: "8px 12px", borderBottom: i < rows.length - 1 ? "1px solid var(--line-soft)" : "none", background: r.best ? "var(--halal-bg)" : "transparent" }}>
          <span style={{ fontWeight: 700, fontSize: 13, color: "var(--ink)" }}>{r.store}</span>
          <span style={{ display: "flex", alignItems: "center", gap: 6 }}>
            {r.best && <span style={{ fontSize: 9.5, fontWeight: 900, color: "var(--halal)", background: "#fff", border: "1px solid var(--halal)", borderRadius: 5, padding: "1px 5px" }}>BEST</span>}
            <span style={{ fontWeight: 900, fontSize: 13.5, color: r.best ? "var(--halal)" : "var(--ink)" }}>{r.price}</span>
          </span>
        </div>
      ))}
    </div>
  );
}

/* Typing dots */
function Typing() {
  return (
    <div className="ac-bubble ac-in" style={{ padding: "12px 14px" }}>
      <div className="ac-typing"><span></span><span></span><span></span></div>
    </div>
  );
}

/* ----------------------------------------------------------
   Chat timeline engine
---------------------------------------------------------- */
const SCRIPT = [
  { from: "me", kind: "text", text: "is this one halal? 👀", wait: 700 },
  { from: "me", kind: "photo", label: "label photo", wait: 650 },
  { from: "adam", typing: 1500, kind: "verdict", status: "halal",
    props: { status: "halal", name: "Crescent Foods Chicken Breast", sub: "Hand-slaughtered, zabiha. Certified.", meta: "Halal Certified · #CA-2241" }, wait: 1700 },
  { from: "me", kind: "text", text: "ayy 🙌 halal shawarma near me?", wait: 1100 },
  { from: "adam", typing: 1400, kind: "restaurants", wait: 1900 },
  { from: "me", kind: "text", text: "cheapest halal chicken this week?", wait: 1100 },
  { from: "adam", typing: 1500, kind: "prices", wait: 2200 },
  { from: "adam", kind: "text", text: "No Frills is your best bet 👍 Want me to check beef too?", wait: 2600 },
];

function ChatDemo() {
  const [items, setItems] = useState([]);
  const [typing, setTyping] = useState(false);
  const scrollRef = useRef(null);
  const timers = useRef([]);

  useEffect(() => {
    let cancelled = false;
    function clearAll() { timers.current.forEach(clearTimeout); timers.current = []; }
    function run() {
      setItems([]); setTyping(false);
      let t = 500;
      SCRIPT.forEach((step) => {
        if (step.typing) {
          timers.current.push(setTimeout(() => !cancelled && setTyping(true), t));
          t += step.typing;
          timers.current.push(setTimeout(() => !cancelled && setTyping(false), t));
        }
        timers.current.push(setTimeout(() => {
          if (cancelled) return;
          setItems((prev) => [...prev, step]);
        }, t));
        t += step.wait;
      });
      // loop
      timers.current.push(setTimeout(() => { if (!cancelled) run(); }, t + 2600));
    }
    run();
    return () => { cancelled = true; clearAll(); };
  }, []);

  useEffect(() => {
    const el = scrollRef.current;
    if (el) el.scrollTop = el.scrollHeight;
  }, [items, typing]);

  return (
    <div className="ac-phone">
      {/* dynamic island / notch */}
      <div className="ac-notch"></div>
      <div className="ac-screen">
        {/* status bar */}
        <div className="ac-status">
          <span>9:41</span>
          <span style={{ display: "flex", gap: 5, alignItems: "center", fontSize: 11 }}>
            <span>●●●</span><span>📶</span><span>96%</span>
          </span>
        </div>
        {/* chat header */}
        <div className="ac-header">
          <div className="ac-avatar"><Tick size={16} /></div>
          <div style={{ lineHeight: 1.15 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 5, fontWeight: 800, fontSize: 15, whiteSpace: "nowrap" }}>
              Adam Checks
              <span className="ac-verified"><Tick size={8} color="#fff" /></span>
            </div>
            <div style={{ fontSize: 11.5, color: "rgba(255,255,255,.85)" }}>online · replies instantly</div>
          </div>
          <div style={{ marginLeft: "auto", display: "flex", gap: 14, opacity: .9, fontSize: 16 }}>
            <span>📞</span><span>⋮</span>
          </div>
        </div>
        {/* messages */}
        <div className="ac-thread" ref={scrollRef}>
          <div className="ac-daystamp">TODAY</div>
          {items.map((m, i) => (
            <MessageRow key={i} m={m} />
          ))}
          {typing && (
            <div className="ac-row ac-row-in"><Typing /></div>
          )}
        </div>
        {/* input */}
        <div className="ac-input">
          <div className="ac-inputbox">Message Adam…</div>
          <div className="ac-send"><svg width="18" height="18" viewBox="0 0 24 24" fill="none"><path d="M4 12l16-8-5 16-3-6-8-2z" fill="#fff"/></svg></div>
        </div>
      </div>
    </div>
  );
}

function MessageRow({ m }) {
  const mine = m.from === "me";
  let inner;
  if (m.kind === "text") inner = <div className={`ac-bubble ${mine ? "ac-out" : "ac-in"}`}>{m.text}<span className="ac-time">{mine ? "9:41 ✓✓" : "9:41"}</span></div>;
  else if (m.kind === "photo") inner = (
    <div className={`ac-bubble ac-out`} style={{ padding: 4 }}>
      <div className="ac-photo"><span>label photo</span></div>
      <span className="ac-time" style={{ paddingRight: 6 }}>9:41 ✓✓</span>
    </div>
  );
  else if (m.kind === "verdict") inner = <div className="ac-bubble ac-in ac-rich"><VerdictCard {...m.props} /></div>;
  else if (m.kind === "restaurants") inner = <div className="ac-bubble ac-in ac-rich"><RestaurantCard /></div>;
  else if (m.kind === "prices") inner = <div className="ac-bubble ac-in ac-rich"><PriceCard /></div>;
  return <div className={`ac-row ${mine ? "ac-row-out" : "ac-row-in"} ac-pop`}>{inner}</div>;
}

window.ChatDemo = ChatDemo;
window.Tick = Tick;
