/* ========================================================================
   screen-webchat.jsx, emirates.com on LAPTOP
   Animated flow:
     home   -> typing-name -> typing-pnr -> submit -> loading
            -> manage (Manage Booking page, with chat FAB peek + 1 unread)
            -> opening -> open (chat widget runs)
   ======================================================================== */

function ScreenWebChat({ active }) {
  const turns = window.DEMO_SCRIPT.web_chat;
  const lukas = window.DEMO_SCRIPT.passenger;
  const hala = window.DEMO_SCRIPT.hala;
  const opts = window.DEMO_SCRIPT.options;
  const dates = window.DEMO_DATES;
  const BOOKING_REF = lukas.booking_ref; // "K7RJ4X"
  const LAST_NAME   = "Weber";

  const PHASES = ["home", "typing-name", "typing-pnr", "submit", "loading", "manage", "opening", "open"];
  const [phase, setPhase] = useState("home");
  const [typedName, setTypedName] = useState("");
  const [typedPnr,  setTypedPnr]  = useState("");
  const timersRef = useRef([]);

  const clearTimers = () => { timersRef.current.forEach(clearTimeout); timersRef.current = []; };
  const after = (ms, fn) => { const id = setTimeout(fn, ms); timersRef.current.push(id); return id; };

  // Choreograph
  useEffect(() => {
    if (!active) {
      clearTimers();
      setPhase("home"); setTypedName(""); setTypedPnr("");
      return;
    }
    clearTimers();
    setPhase("home"); setTypedName(""); setTypedPnr("");

    // Faster intro pacing, get to the chat quickly.
    after(900, () => setPhase("typing-name"));

    const FULLNAME = LAST_NAME; // "Weber", 5 chars
    FULLNAME.split("").forEach((ch, i) => {
      after(900 + 200 + i * 90, () => setTypedName(FULLNAME.slice(0, i + 1)));
    });

    // 900 + 200 + 5*90 = 1550 -> switch to PNR field
    after(1700, () => setPhase("typing-pnr"));

    const FULLPNR = BOOKING_REF; // "K7RJ4X", 6 chars
    FULLPNR.split("").forEach((ch, i) => {
      after(1700 + 200 + i * 90, () => setTypedPnr(FULLPNR.slice(0, i + 1)));
    });

    // 1700 + 200 + 7*90 = 2530 -> submit
    after(2700, () => setPhase("submit"));
    after(3000, () => setPhase("loading"));
    after(3700, () => setPhase("manage"));
    // FAB peek for ~1.8s, then open
    after(5500, () => setPhase("opening"));
    after(6100, () => setPhase("open"));

    const skip = () => {
      clearTimers();
      setTypedName(LAST_NAME); setTypedPnr(BOOKING_REF);
      setPhase("open");
    };
    window.addEventListener("demo:skip", skip);
    return () => { clearTimers(); window.removeEventListener("demo:skip", skip); };
  }, [active]);

  const openWidget = () => {
    if (phase !== "manage") return;
    clearTimers();
    setPhase("opening");
    after(700, () => setPhase("open"));
  };

  // Readable playback pace (1.0x = script time exactly).
  const { shown, typing } = window.useChatPlayback(turns, {
    sceneActive: active && phase === "open", paused: false, speed: 1.0,
  });

  // Smart auto-scroll: only follow the latest message if the user is already pinned
  // to the bottom. If they have scrolled up to re-read something, leave them alone.
  const feedRef = useRef(null);
  const pinnedRef = useRef(true); // assume pinned at start

  const handleFeedScroll = () => {
    const el = feedRef.current;
    if (!el) return;
    const dist = el.scrollHeight - el.scrollTop - el.clientHeight;
    pinnedRef.current = dist < 48; // within 48px of bottom counts as "pinned"
  };

  useEffect(() => {
    const el = feedRef.current;
    if (!el) return;
    if (pinnedRef.current) {
      el.scrollTop = el.scrollHeight;
    }
  }, [shown, typing]);

  // Cursor target by phase
  const cursorPos = (() => {
    switch (phase) {
      case "home":         return { x: "47%", y: "62%" };  // moving toward last-name
      case "typing-name":  return { x: "47%", y: "70%" };  // hovering near last-name
      case "typing-pnr":   return { x: "60%", y: "70%" };  // hovering near pnr
      case "submit":       return { x: "75%", y: "70%" };  // on Manage booking button
      case "loading":      return { x: "75%", y: "70%" };
      case "manage":       return { x: "92%", y: "92%" };  // moving to FAB
      case "opening":
      case "open":         return { x: "92%", y: "92%" };
      default:             return { x: "50%", y: "50%" };
    }
  })();

  const showHomepage = ["home","typing-name","typing-pnr","submit","loading"].includes(phase);
  const showManage   = ["manage","opening","open"].includes(phase);

  // URL bar text changes by phase
  const urlText = showHomepage ? "emirates.com" : `emirates.com/manage-booking · ${BOOKING_REF}`;
  const tabText = showHomepage ? "Emirates · Fly Better" : "Emirates · Manage Booking";

  return (
    <div className="canvas canvas-paper">
      <PhaseTag label={
        showHomepage ? "Channel · emirates.com · home"
        : showManage && phase === "manage" ? "Channel · emirates.com / Manage Booking"
        : "Channel · emirates.com / Manage Booking · web chat with Hala"
      }/>

      <div className="web-stage">
        <div className="laptop fade-in">
          <div className="laptop-screen">
            <div className="laptop-window">
              <div className="browser-chrome">
                <div className="lights"><span/><span/><span/></div>
                <div className="navs">
                  <FlatIcon name="chevronRight" size={14} stroke="#9aa0aa" style={{transform: "rotate(180deg)"}}/>
                  <FlatIcon name="chevronRight" size={14} stroke="#9aa0aa"/>
                  <FlatIcon name="refresh" size={14} stroke="#9aa0aa"/>
                </div>
                <div className="tabs">
                  <div className="tab"><img src="assets/emirates-logo.png" alt="" style={{height: 12, width: "auto", verticalAlign: "middle", marginRight: 6}}/>{tabText}</div>
                </div>
                <div className="url"><FlatIcon name="lock" size={11} stroke="#6b7079"/> {urlText}</div>
                <div style={{flex: 1}}/>
              </div>

              <div className="site-viewport">
                {/* HOMEPAGE LAYER */}
                {showHomepage && (
                  <div className="ek-home fade-in">
                    <EkHeader/>
                    <div className="ek-hero">
                      <div className="ek-hero-overlay">
                        <div className="ek-hero-eyebrow">Enjoy flexible travel with</div>
                        <div className="ek-hero-title">A FREE DATE CHANGE</div>
                        <div className="ek-hero-sub">on all new tickets</div>
                        <button className="ek-hero-cta">Book now</button>
                      </div>
                      <div className="ek-hero-flybetter">FLY BETTER</div>
                    </div>

                    <div className="ek-search-card">
                      <div className="ek-search-tabs">
                        <div className="ek-stab"><FlatIcon name="plane" size={14} stroke="#444"/> Search flights</div>
                        <div className="ek-stab is-active">Manage booking / Check in</div>
                        <div className="ek-stab"><FlatIcon name="plane" size={14} stroke="#444"/> What's on your flight</div>
                        <div className="ek-stab">Flight status</div>
                      </div>
                      <div className="ek-search-body">
                        <div className="ek-help-line">Log in to view your trips</div>
                        <div className="ek-form-row">
                          <div className={`ek-input ${phase === "typing-name" ? "is-focused" : ""}`}>
                            <span className="ek-input-label">Last name</span>
                            <span className="ek-input-value">
                              {typedName}
                              {phase === "typing-name" && <span className="ek-caret"/>}
                            </span>
                          </div>
                          <div className={`ek-input ${phase === "typing-pnr" ? "is-focused" : ""}`}>
                            <span className="ek-input-label">Booking reference</span>
                            <span className="ek-input-value">
                              {typedPnr}
                              {phase === "typing-pnr" && <span className="ek-caret"/>}
                            </span>
                          </div>
                          <button className={`ek-submit ${phase === "submit" ? "is-pressed" : ""}`}>Manage booking</button>
                          <button className="ek-submit ek-submit--ghost">Check in</button>
                        </div>
                      </div>
                    </div>

                    <div className="ek-quick-row">
                      {["Hotels","Car rentals","Tours & activities","Book a holiday","Chauffeur drive","Meet & greet"].map(t => (
                        <div key={t} className="ek-quick"><div className="ek-quick-ico"/><span>{t}</span></div>
                      ))}
                    </div>

                    <div className="ek-featured">
                      <div className="ek-featured-h">Featured destinations from <b>Dubai</b></div>
                      <div className="ek-featured-grid">
                        {[
                          {city:"Singapore", price:"AED 2,820"},
                          {city:"Munich",    price:"AED 3,090"},
                          {city:"Osaka",     price:"AED 5,410"},
                        ].map(d => (
                          <div key={d.city} className="ek-dest">
                            <div className="ek-dest-img" data-city={d.city}/>
                            <div className="ek-dest-meta">
                              <div className="ek-dest-city">{d.city}</div>
                              <div className="ek-dest-price">from {d.price}*</div>
                            </div>
                          </div>
                        ))}
                      </div>
                    </div>

                    {/* Loading veil */}
                    {phase === "loading" && (
                      <div className="ek-loading">
                        <div className="ek-spinner"/>
                        <div className="ek-loading-t">Loading your booking…</div>
                      </div>
                    )}
                  </div>
                )}

                {/* MANAGE BOOKING LAYER */}
                {showManage && (
                  <div className="ek-manage fade-in">
                    <EkHeader signedIn={lukas.first}/>

                    <div className="ek-mb-hero">
                      <div className="ek-mb-eyebrow">My trips</div>
                      <div className="ek-mb-title">Hello, {lukas.first}</div>
                      <div className="ek-mb-sub">Booking reference <b>{BOOKING_REF}</b> · Skywards Silver</div>
                    </div>

                    <div className="ek-mb-card">
                      <div className="ek-mb-cancel-banner">
                        <div className="ek-mb-cancel-ico">!</div>
                        <div>
                          <div className="ek-mb-cancel-t">Your flight EK202 has been cancelled</div>
                          <div className="ek-mb-cancel-s">Your ticket is still valid. We've held your fare and seat preference. Choose a new flight at no extra cost, or request a refund.</div>
                        </div>
                      </div>

                      <div className="ek-mb-flight">
                        <div className="ek-mb-flight-head">
                          <div className="ek-mb-flight-rt">EK202 · Dubai → New York</div>
                          <div className="ek-mb-flight-status">CANCELLED</div>
                        </div>
                        <div className="ek-mb-flight-times">
                          <div>
                            <div className="ek-mb-time">08:30</div>
                            <div className="ek-mb-code">DXB</div>
                            <div className="ek-mb-place">Dubai Intl · {dates.TODAY_LONG}</div>
                          </div>
                          <div className="ek-mb-arrow">
                            <div className="ek-mb-arrow-line"/>
                            <FlatIcon name="plane" size={18} stroke="#A8111A"/>
                            <div className="ek-mb-arrow-line"/>
                          </div>
                          <div>
                            <div className="ek-mb-time">13:45</div>
                            <div className="ek-mb-code">JFK</div>
                            <div className="ek-mb-place">John F. Kennedy · {dates.TODAY_LONG}</div>
                          </div>
                        </div>

                        <div className="ek-mb-actions">
                          <button className="ek-mb-action ek-mb-action--primary">Choose a new flight</button>
                          <button className="ek-mb-action">Request refund</button>
                          <button className="ek-mb-action">Call Emirates</button>
                        </div>
                      </div>

                      <div className="ek-mb-passenger">
                        <div className="ek-mb-passenger-h">Passenger</div>
                        <div className="ek-mb-passenger-row">
                          <div className="ek-mb-pa-av">LW</div>
                          <div>
                            <div className="ek-mb-pa-name">Lukas Weber</div>
                            <div className="ek-mb-pa-meta">Skywards Silver · Seat 23A · Meal: vegetarian</div>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                )}

                {/* CURSOR */}
                <div
                  className={`ek-cursor phase-${phase}`}
                  style={{ left: cursorPos.x, top: cursorPos.y }}
                  aria-hidden
                >
                  <svg width="22" height="26" viewBox="0 0 22 26" fill="none">
                    <path d="M2 2 L2 20 L7 16 L10 24 L13 23 L10 15 L17 14 Z" fill="#1a1a1c" stroke="white" strokeWidth="1.4" strokeLinejoin="round"/>
                  </svg>
                </div>

                {/* CHAT FAB, visible only on manage page, before opening */}
                <button
                  className={`chat-fab ${phase === "manage" ? "is-visible is-pulsing" : ""}`}
                  onClick={openWidget}
                  aria-label="Chat with Hala"
                  style={phase === "manage" ? {opacity: 1, transform: "translateY(0) scale(1)", pointerEvents: "auto"} : {opacity: 0, transform: "translateY(14px) scale(0.85)", pointerEvents: "none"}}
                >
                  <span className="fab-ring"/>
                  <img src={hala.photo} alt=""/>
                  <span className="fab-badge">1</span>
                  {phase === "manage" && (
                    <span className="fab-peek">
                      <span className="fab-peek-name">Hala · Emirates</span>
                      <span className="fab-peek-text">Hi Lukas, I see your flight was cancelled. Want me to find you another?</span>
                    </span>
                  )}
                </button>

                <div className={`chat-widget cw-${phase === "open" || phase === "opening" ? phase : "page"}`}>
                  <div className="cw-header">
                    <div className="av"><img src={hala.photo} alt=""/></div>
                    <div className="who">
                      <div className="name">{hala.name}</div>
                      <div className="status"><span className="dot"/>Online · Replies instantly</div>
                    </div>
                    <div className="ai-badge">
                      <span style={{width: 5, height: 5, background: "white", borderRadius: 999, animation: "blink 1.6s infinite"}}/>
                      Virtual Assistant
                    </div>
                    <span className="x">−</span>
                  </div>

                  <div className="cw-feed" ref={feedRef} onScroll={handleFeedScroll}>
                    {shown.map((t, i) => {
                      if (t.who === "hala") {
                        return (
                          <div key={i} className="bubble-row">
                            <div className="av"><img src={hala.photo} alt=""/></div>
                            <div style={{display: "flex", flexDirection: "column"}}>
                              <div className="bubble from-hala">
                                {t.text}
                              </div>
                              <div className="chat-time">{t.t}</div>
                            </div>
                          </div>
                        );
                      }
                      if (t.who === "lukas") {
                        const cls = "bubble from-user" + (t.tone === "stressed" ? " tone-stressed" : t.tone === "personal" ? " tone-personal" : "");
                        return (
                          <div key={i} className="bubble-row from-user">
                            <div style={{display: "flex", flexDirection: "column", alignItems: "flex-end"}}>
                              <div className={cls}>{t.text}</div>
                              <div className="chat-time">{t.t}</div>
                            </div>
                          </div>
                        );
                      }
                      if (t.who === "system") {
                        return <div key={i} className="chat-system"><span className="dot dot--ai"/>{t.text}</div>;
                      }
                      if (t.who === "options") {
                        return (
                          <div key={i} className="bubble-row">
                            <div className="av"><img src={hala.photo} alt=""/></div>
                            <div className="chat-options-card">
                              {opts.map(o => (
                                <div key={o.id} className={`opt ${o.starred ? "starred" : ""} ${o.warn ? "warn-opt" : ""}`}>
                                  <div className="opt-tag">
                                    {o.starred && <span className="opt-rec">RECOMMENDED</span>}
                                    {o.label}
                                  </div>
                                  <div className="opt-rt">{o.flight}</div>
                                  <div className="opt-times">{o.from} {o.depart_time} → {o.to} {o.arrive_time}<span style={{color: "var(--ink-3)"}}> · {o.depart_date}</span></div>
                                  <div className="opt-meta">
                                    <span className={o.seats_warn ? "warn" : ""}>{o.seats_available} seats · {o.stops}</span>
                                    <span style={{color: o.warn ? "var(--bad)" : "var(--good)"}}>{o.fare_diff}</span>
                                  </div>
                                  {o.reason && (
                                    <div className={`opt-reason ${o.starred ? "is-rec" : o.warn ? "is-warn" : ""}`}>
                                      <FlatIcon name={o.warn ? "warn" : "sparkle"} size={12} stroke={o.warn ? "#c63a3a" : "#9b6a17"}/>
                                      <span>{o.reason}</span>
                                    </div>
                                  )}
                                </div>
                              ))}
                              <div className="opts-foot">
                                <FlatIcon name="sparkle" size={11} stroke="#9b6a17"/>
                                <span>Ranked using what you told me about tomorrow.</span>
                              </div>
                            </div>
                          </div>
                        );
                      }
                      if (t.who === "seat-hold") {
                        return (
                          <div key={i} className="bubble-row">
                            <div className="av"><img src={hala.photo} alt=""/></div>
                            <div className="chat-seat-hold">
                              <div className="seat-hold-ico">23A</div>
                              <div className="seat-hold-body">
                                <div className="seat-hold-t">Preference noted · seat 23A</div>
                                <div className="seat-hold-s">Hold placed, awaiting specialist approval</div>
                              </div>
                              <FlatIcon name="clock" size={14} stroke="#9b6a17"/>
                            </div>
                          </div>
                        );
                      }
                      if (t.who === "channel-choice") {
                        return (
                          <div key={i} className="bubble-row">
                            <div className="av"><img src={hala.photo} alt=""/></div>
                            <div className="chat-channel-choice">
                              <div className="cc-opt cc-opt--active">
                                <div className="cc-opt-ico"><FlatIcon name="phone" size={16} stroke="var(--ek-red)"/></div>
                                <div>
                                  <div className="cc-opt-t">Call you on your number</div>
                                  <div className="cc-opt-s">Hala rings +971 50 ••• 4421, no hold, no dialling</div>
                                </div>
                              </div>
                              <div className="cc-opt">
                                <div className="cc-opt-ico"><FlatIcon name="phone" size={16} stroke="#666"/></div>
                                <div>
                                  <div className="cc-opt-t">Continue on web voice</div>
                                  <div className="cc-opt-s">Stay in this chat and switch to voice in-browser</div>
                                </div>
                              </div>
                            </div>
                          </div>
                        );
                      }
                      if (t.who === "call-cta") {
                        return (
                          <div key={i} className="chat-tap-call">
                            <div className="ico"><FlatIcon name="phone" size={18} stroke="var(--ek-red)"/></div>
                            <div className="body">
                              <div className="ttl">Calling {lukas.first} now …</div>
                              <div className="sub">Full chat context comes with you</div>
                            </div>
                            <span className="ring-dot"/>
                          </div>
                        );
                      }
                      return null;
                    })}

                    {typing?.who === "hala" && (
                      <div className="bubble-row">
                        <div className="av"><img src={hala.photo} alt=""/></div>
                        <div className="bubble is-typing">
                          <div className="typing-dots"><span/><span/><span/></div>
                        </div>
                      </div>
                    )}
                    {typing?.who === "lukas" && (
                      <div className="bubble-row from-user">
                        <div className="bubble from-user is-typing">
                          <div className="typing-dots" style={{color: "white"}}><span/><span/><span/></div>
                        </div>
                      </div>
                    )}
                  </div>

                  <div className="cw-composer">
                    <div className="input">Message Hala…</div>
                    <div className="send"><FlatIcon name="send" size={14} stroke="white"/></div>
                  </div>
                  <div className="cw-foot">
                    <span style={{color: "var(--ink-3)", fontSize: 11}}>Powered by</span>
                    <img src="assets/wonderful-logo.png" alt="Wonderful" style={{height: 11, opacity: 0.7}}/>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div className="laptop-base"/>
        </div>
      </div>
    </div>
  );
}

/* Inline highlight: wrap any occurrence of `phrase` in <mark>. */
function renderWithHighlight(text, phrase) {
  if (!phrase) return text;
  const i = text.indexOf(phrase);
  if (i === -1) return text;
  return (
    <>
      {text.slice(0, i)}
      <mark className="chat-hl">{phrase}</mark>
      {text.slice(i + phrase.length)}
    </>
  );
}

/* ---------- Header subcomponent ---------- */
function EkHeader({ signedIn }) {
  return (
    <>
      <div className="ek-strip">
        <span>● Important</span>
        <span style={{marginLeft: 8, color: "#444"}}>Travel advisory · Changes to certain operating schedules</span>
        <span style={{marginLeft: "auto", color: "#666"}}>Show more ▾</span>
      </div>
      <div className="ek-nav">
        <img src="assets/emirates-logo.png" alt="Emirates" className="ek-logo"/>
        <div className="ek-nav-items">
          <span>BOOK</span><span>MANAGE</span><span>EXPERIENCE</span><span>WHERE WE FLY</span><span>LOYALTY</span><span>HELP</span>
        </div>
        <div className="ek-nav-right">
          <span>AE</span>
          <span>EN</span>
          <span>{signedIn ? `👤 ${signedIn}` : "👤 LOG IN"}</span>
        </div>
      </div>
    </>
  );
}

window.ScreenWebChat = ScreenWebChat;
