/* Hand Hub — Live Simulation
   Recreates the Veo3 / Google Flow dark UI and animates an AI cursor
   driving every manual click, type, upload, submit. The point is to
   make the viewer FEEL: "the robot is doing my hands' work." */

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

// ── Step script (one platform loop) ─────────────────────────────────
// Each step describes: (a) what the cursor does, (b) what mutates on screen,
// (c) the human-readable caption shown below the browser.
const PROMPT_TEXT = "Cinematic wide shot, vịnh Hạ Long sương sớm, drone bay chậm trên mặt nước, ánh nắng vàng xuyên qua các đảo đá vôi, máy quay tiến chậm";

const PLATFORMS = {
  veo3:  { url: "labs.google/fx/vi/tools/flow", profile: "veo3",  label: "Veo 3 · Google Flow" },
  grok:  { url: "grok.com/imagine",        profile: "grok",  label: "Grok Imagine" },
  kling: { url: "klingai.com/text-to-video", profile: "kling", label: "Kling AI" },
};

const STEPS = [
  { id: 1,  cap: "Mở Chrome profile",          detail: "Veo 3 · profile=veo3",  target: "url",        wait: 900 },
  { id: 2,  cap: "Click vào ô prompt",         detail: "contenteditable[role=textbox]", target: "promptBox",  click: true, wait: 700 },
  { id: 3,  cap: "Bấm nút '+' để mở cài đặt",  detail: "click button[aria-label=add]", target: "plus",       click: true, wait: 700, mutate: { menu: true } },
  { id: 4,  cap: "Chọn loại 'Video'",          detail: "menuitem · type=video", target: "menuVideo",   click: true, wait: 600, mutate: { type: "video" } },
  { id: 5,  cap: "Chọn 'Khung hình'",          detail: "menuitem · mode=frame", target: "menuFrame",   click: true, wait: 600, mutate: { mode: "frame" } },
  { id: 6,  cap: "Chọn tỷ lệ 16:9",            detail: "aspect=16:9",           target: "menu169",     click: true, wait: 600, mutate: { aspect: "16:9" } },
  { id: 7,  cap: "Chọn model 'Veo 3.1 - Lite'", detail: "model=Veo3.1-Lite",    target: "menuModel",   click: true, wait: 600 },
  { id: 8,  cap: "Chọn thời lượng 8s",         detail: "duration=8s",           target: "menu8s",      click: true, wait: 700, mutate: { dur: "8s" } },
  { id: 9,  cap: "Đóng menu, quay về prompt",  detail: "esc · focus textarea",  target: "promptBox",   click: true, wait: 700, mutate: { menu: false, focus: true } },
  { id: 10, cap: "Gõ prompt 142 ký tự",        detail: "type · 38 wpm jitter",  target: "promptBox",   wait: 2400, mutate: { typing: true } },
  { id: 11, cap: "Bấm nút gửi",                detail: "click button[arrow]",   target: "submit",      click: true, wait: 800, mutate: { typing: false, armed: true } },
  { id: 12, cap: "Chờ render — 28%",           detail: "polling DOM · video src", target: "thumb",     wait: 1100, mutate: { armed: false, thumb: 28 } },
  { id: 13, cap: "Render xong, tải về máy",    detail: "~/Videos/Veo3/job_1.mp4", target: "thumb",     wait: 900,  mutate: { thumb: 100 } },
  { id: 14, cap: "Sang job kế trong hàng đợi",  detail: "next job · giữ profile veo3", target: "url",        wait: 900, mutate: { reset: true, platform: "veo3" } },
];

// ── Hit-test coordinates inside the 760×460 browser canvas ──────────
// Adjusted so the cursor lands on real-looking UI element centers.
const COORDS = {
  url:        { x: 320, y: 26  },
  promptBox:  { x: 360, y: 388 },
  plus:       { x: 100, y: 422 },
  menuVideo:  { x: 605, y: 226 },
  menuFrame:  { x: 480, y: 268 },
  menu169:    { x: 605, y: 312 },
  menuModel:  { x: 540, y: 354 },
  menu8s:     { x: 615, y: 396 },
  submit:     { x: 632, y: 422 },
  thumb:      { x: 130, y: 110 },
};

// ── Pixel flower — recreated from screenshot ───────────────────────
// 8×8 grid; 1 = pixel on, 0 = off
const FLOWER = [
  "00111100",
  "01111110",
  "11000011",
  "11000011",
  "01111110",
  "00011000",
  "00111100",
  "00000000",
];

function PixelFlower() {
  return (
    <div className="flow-pixel-flower">
      {FLOWER.flatMap((row, r) =>
        row.split("").map((c, i) => (
          <span key={r + "-" + i} className={c === "1" ? "" : "off"} />
        ))
      )}
    </div>
  );
}

// ── Icons ──────────────────────────────────────────────────────────
const Ico = {
  back:  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeLinecap="round" strokeLinejoin="round"><path d="M15 18 L9 12 L15 6"/></svg>,
  search:<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeLinecap="round" strokeLinejoin="round"><circle cx="11" cy="11" r="7"/><path d="M21 21 L16.5 16.5"/></svg>,
  plus:  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeLinecap="round" strokeLinejoin="round"><path d="M12 5 V19 M5 12 H19"/></svg>,
  film:  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="6" width="18" height="12" rx="2"/><path d="M7 6 V18 M17 6 V18"/></svg>,
  gear:  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.7 1.7 0 0 0 .3 1.8l.1.1a2 2 0 0 1-2.8 2.8l-.1-.1a1.7 1.7 0 0 0-1.8-.3 1.7 1.7 0 0 0-1 1.5V21a2 2 0 0 1-4 0v-.1a1.7 1.7 0 0 0-1.1-1.5 1.7 1.7 0 0 0-1.8.3l-.1.1a2 2 0 0 1-2.8-2.8l.1-.1a1.7 1.7 0 0 0 .3-1.8 1.7 1.7 0 0 0-1.5-1H3a2 2 0 0 1 0-4h.1a1.7 1.7 0 0 0 1.5-1.1 1.7 1.7 0 0 0-.3-1.8l-.1-.1a2 2 0 0 1 2.8-2.8l.1.1a1.7 1.7 0 0 0 1.8.3H9a1.7 1.7 0 0 0 1-1.5V3a2 2 0 0 1 4 0v.1a1.7 1.7 0 0 0 1 1.5 1.7 1.7 0 0 0 1.8-.3l.1-.1a2 2 0 0 1 2.8 2.8l-.1.1a1.7 1.7 0 0 0-.3 1.8V9a1.7 1.7 0 0 0 1.5 1H21a2 2 0 0 1 0 4h-.1a1.7 1.7 0 0 0-1.5 1z"/></svg>,
  help:  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="9"/><path d="M9.5 9 a2.5 2.5 0 0 1 5 0 c0 2-2.5 2.5-2.5 4"/><circle cx="12" cy="17" r="0.5" fill="currentColor"/></svg>,
  more:  <svg viewBox="0 0 24 24" fill="currentColor"><circle cx="12" cy="5" r="1.5"/><circle cx="12" cy="12" r="1.5"/><circle cx="12" cy="19" r="1.5"/></svg>,
  sliders:<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeLinecap="round" strokeLinejoin="round"><path d="M4 6 H20 M4 12 H14 M4 18 H10"/></svg>,
  arrowR: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeLinecap="round" strokeLinejoin="round" strokeWidth="2.5"><path d="M5 12 H19"/><path d="M13 6 L19 12 L13 18"/></svg>,
  grid:  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="3" width="7" height="7" rx="1"/><rect x="14" y="3" width="7" height="7" rx="1"/><rect x="3" y="14" width="7" height="7" rx="1"/><rect x="14" y="14" width="7" height="7" rx="1"/></svg>,
  download:<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeLinecap="round" strokeLinejoin="round"><path d="M12 3 V15"/><path d="M7 10 L12 15 L17 10"/><path d="M4 19 H20"/></svg>,
  image: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="5" width="18" height="14" rx="2"/><circle cx="8.5" cy="10.5" r="1.5"/><path d="M3 17 L9 12 L15 17 L21 13"/></svg>,
  videoIc:<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="9"/><polygon points="10,8 17,12 10,16" fill="currentColor"/></svg>,
  frame: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeLinecap="round" strokeLinejoin="round"><rect x="6" y="3" width="12" height="18" rx="2"/></svg>,
  compose:<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeLinecap="round" strokeLinejoin="round"><path d="M9 4 L4 9 L9 14"/><path d="M15 10 L20 15 L15 20"/></svg>,
  phone: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeLinecap="round" strokeLinejoin="round"><rect x="7" y="3" width="10" height="18" rx="2"/></svg>,
};

// ── AI cursor with robot tag ────────────────────────────────────────
function AICursor({ x, y, label, ripple }) {
  return (
    <>
      {ripple !== null && (
        <span key={ripple} className="ai-ripple" style={{ left: x, top: y }} />
      )}
      <div className="ai-cursor" style={{ left: x, top: y }}>
        <svg viewBox="0 0 24 24">
          <path d="M5 3 L5 19 L9.5 15 L12 21 L14.5 20 L12 14 L18 14 Z"
                fill="#fff" stroke="#0F0F10" strokeWidth="1.4" strokeLinejoin="round"/>
        </svg>
        <span className="robot-tag">Hand Hub</span>
      </div>
    </>
  );
}

// ── The fake Flow dark UI ──────────────────────────────────────────
function FlowPage({ s, typed }) {
  const promptText = typed > 0 ? PROMPT_TEXT.slice(0, typed) : "";
  const showPlaceholder = !s.typing && promptText.length === 0;
  return (
    <div className="flow-shell">
      {/* top toolbar */}
      <div className="flow-top">
        <button className="icon-btn">{Ico.back}</button>
        <span className="stamp">May 09, 09:51 PM</span>
        <button className="icon-btn">{Ico.more}</button>
        <div className="search">{Ico.search}<span> </span></div>
        <button className="icon-btn">{Ico.sliders}</button>
        <button className="icon-btn" data-spot="plus-top">{Ico.plus}</button>
        <button className="icon-btn">{Ico.film}</button>
        <button className="icon-btn">{Ico.gear}</button>
        <button className="icon-btn">{Ico.help}</button>
        <button className="icon-btn">{Ico.more}</button>
        <div className="right">
          <span className="ultra-badge">ULTRA</span>
          <span className="avatar">d</span>
        </div>
      </div>

      {/* left rail */}
      <div className="flow-rail">
        <div className="rail-btn active">{Ico.grid}</div>
        <div className="rail-btn">{Ico.image}</div>
        <div className="rail-btn">{Ico.compose}</div>
      </div>

      {/* stage */}
      <div className="flow-stage">
        {/* loading thumbnail */}
        <div className={"flow-thumb " + (s.thumb > 0 ? "show" : "")}>
          <div className="ico">{Ico.image}</div>
          <span className="pct">{s.thumb}%</span>
          {s.thumb > 0 && s.thumb < 100 && <div className="shimmer"></div>}
        </div>

        {!s.thumb && (
          <div className="flow-empty">
            <PixelFlower/>
            <div className="tagline">Bắt đầu tạo hoặc thả nội dung nghe nhìn</div>
          </div>
        )}
      </div>

      {/* settings popup */}
      <div className={"flow-settings " + (s.menu ? "show" : "")}>
        <div className="pair">
          <div className={"opt " + (s.type !== "video" ? "active" : "")}>{Ico.image} Hình ảnh</div>
          <div className={"opt " + (s.type === "video" ? "active" : "") + (s.armedKey === "menuVideo" ? " armed" : "")}>{Ico.videoIc} Video</div>
        </div>
        <div className="pair">
          <div className={"opt " + (s.mode === "frame" ? "active" : "") + (s.armedKey === "menuFrame" ? " armed" : "")}>{Ico.frame} Khung hình</div>
          <div className={"opt " + (s.mode === "compose" ? "active" : "")}>{Ico.compose} Thành phần</div>
        </div>
        <div className="pair">
          <div className={"opt aspect " + (s.aspect === "9:16" ? "active" : "")}><span className="glyph">▯</span> 9:16</div>
          <div className={"opt aspect " + (s.aspect === "16:9" ? "active" : "") + (s.armedKey === "menu169" ? " armed" : "")}><span className="glyph">▭</span> 16:9</div>
        </div>
        <div className="row-4">
          <div className="opt active">1x</div>
          <div className="opt">x2</div>
          <div className="opt">x3</div>
          <div className="opt">x4</div>
        </div>
        <div className={"model " + (s.armedKey === "menuModel" ? "armed" : "")}>
          <span>Veo 3.1 - Lite</span>
          <span className="caret">▾</span>
        </div>
        <div className="row-3">
          <div className="opt">4s</div>
          <div className="opt">6s</div>
          <div className={"opt " + (s.dur === "8s" ? "active" : "") + (s.armedKey === "menu8s" ? " armed" : "")}>8s</div>
        </div>
        <div className="credits">Quá trình tạo sẽ tốn <b>5 tín dụng</b></div>
      </div>

      {/* prompt bar */}
      <div className={"flow-prompt " + (s.focus || s.typing ? "focused" : "")}>
        <div className={"text " + (showPlaceholder ? "placeholder" : "typed")}>
          {showPlaceholder ? "Bạn muốn tạo gì?" : promptText}
          {s.typing && <span className="caret"></span>}
        </div>
        <div className="row">
          <button className={"plus " + (s.armedKey === "plus" ? "active" : "")}>+</button>
          <div className="right">
            <span className="video-pill">Video <span className="glyph">▯</span> 1x</span>
            <button className={"arrow " + (s.armed ? "armed" : "")}>{Ico.arrowR}</button>
          </div>
        </div>
      </div>
      <div className="flow-disclaimer">Flow có thể mắc sai sót nên bạn hãy xác minh nội dung do công cụ này tạo</div>
    </div>
  );
}

// ── Queue model ────────────────────────────────────────────────────
const QUEUE = [
  { id: 1, title: "Hạ Long bay sương sớm",         platform: "veo3" },
  { id: 2, title: "Phố cổ Hội An đèn lồng đêm",   platform: "veo3" },
  { id: 3, title: "Cận cảnh hoa sen nở chậm",     platform: "veo3" },
  { id: 4, title: "Drone biển Phú Quốc hoàng hôn", platform: "veo3" },
  { id: 5, title: "Trẻ thả diều ruộng bậc thang",  platform: "veo3" },
  { id: 6, title: "Cà phê sữa đá nhỏ giọt",       platform: "veo3" },
];

// ── Main component ─────────────────────────────────────────────────
function Simulation() {
  const [stepIdx, setStepIdx] = useState(0);
  const [paused, setPaused] = useState(false);
  const [rippleKey, setRippleKey] = useState(null);
  const [typed, setTyped] = useState(0);
  const [activeJob, setActiveJob] = useState(0);
  const [cursorTarget, setCursorTarget] = useState("url");
  const [armedKey, setArmedKey] = useState(null);

  // Aggregated state passed to FlowPage
  const [state, setState] = useState({
    menu: false, type: "video", mode: "frame", aspect: "16:9",
    dur: "8s", focus: false, typing: false, armed: false,
    thumb: 0, platform: "veo3"
  });

  // Step driver
  useEffect(() => {
    if (paused) return;
    const step = STEPS[stepIdx];
    const target = step.target;
    setCursorTarget(target);
    setArmedKey(target);

    let typingTimer;
    const advance = setTimeout(() => {
      if (step.click) {
        setRippleKey(Date.now());
      }
      // Apply mutations
      if (step.mutate) {
        if (step.mutate.reset) {
          // job done — bump activeJob and reset visuals after a beat
          setTimeout(() => {
            setActiveJob(j => Math.min(j + 1, QUEUE.length - 1));
            setState({
              menu: false, type: "video", mode: "frame", aspect: "16:9",
              dur: "8s", focus: false, typing: false, armed: false,
              thumb: 0, platform: step.mutate.platform || "veo3"
            });
            setTyped(0);
          }, 300);
        } else {
          setState(s => ({ ...s, ...step.mutate }));
        }
      }
      // After step.wait, advance
      const cont = setTimeout(() => {
        setArmedKey(null);
        setStepIdx(i => (i + 1) % STEPS.length);
      }, step.wait);
      return () => clearTimeout(cont);
    }, 240);

    // Type animation during step 10
    if (step.mutate && step.mutate.typing) {
      const total = PROMPT_TEXT.length;
      let i = 0;
      typingTimer = setInterval(() => {
        i += Math.random() < 0.5 ? 2 : 3;
        setTyped(Math.min(i, total));
        if (i >= total) clearInterval(typingTimer);
      }, step.wait / (total / 2.5));
    }
    if (!step.mutate || !step.mutate.typing) {
      // Reset typed when starting a new platform loop
      if (step.mutate && step.mutate.reset) setTyped(0);
    }

    return () => {
      clearTimeout(advance);
      if (typingTimer) clearInterval(typingTimer);
    };
  }, [stepIdx, paused]);

  // Pass armedKey through state for FlowPage
  const flowState = { ...state, armedKey };

  // Cursor coordinates
  const coords = COORDS[cursorTarget] || COORDS.url;

  // Active platform / URL
  const platform = PLATFORMS[state.platform] || PLATFORMS.veo3;

  return (
    <div className="sim-shell-v2" data-screen-label="Simulation · Hand Hub">
      <div className="sim-grid-v2">
        {/* LEFT side */}
        <aside className="sim-side-v2">
          <div className="side-head">
            <span className="title">Hand Hub · Auto Driver</span>
            <span style={{display:"inline-flex",alignItems:"center",gap:6,fontFamily:"var(--font-mono)",fontSize:10,letterSpacing:1,color:"var(--violet)",fontWeight:600}}>
              <span style={{width:6,height:6,borderRadius:"50%",background:"var(--violet)",boxShadow:"0 0 0 3px var(--violet-glow)",animation:"pulse-violet 1.6s ease-in-out infinite"}}></span>
              ĐANG CHẠY
            </span>
          </div>

          <div className="side-section">
            <h5>Hàng đợi · 6 job</h5>
            <div className="q-list">
              {QUEUE.map((j, i) => {
                const status = i < activeJob ? "ok" : i === activeJob ? "run" : "cho";
                const cls = status === "ok" ? "done" : status === "run" ? "active" : "";
                return (
                  <div key={j.id} className={"q-row " + cls}>
                    <span className="q-num">{String(i+1).padStart(2,"0")}</span>
                    <span className={"q-dot " + j.platform}></span>
                    <div className="q-body">
                      <div className="q-title">{j.title}</div>
                      <div className="q-meta">{PLATFORMS[j.platform].label}</div>
                    </div>
                    <span className={"q-status " + status}>
                      {status === "ok" ? "Xong" : status === "run" ? "Chạy" : "Chờ"}
                    </span>
                  </div>
                );
              })}
            </div>
          </div>

          <div className="side-section" style={{flex:1, overflow:"hidden"}}>
            <h5>Robot đang thao tác</h5>
            <div className="step-ticker">
              {STEPS.slice(0, 13).map((st, i) => {
                const cls = i < stepIdx ? "done" : i === stepIdx ? "active" : "todo";
                return (
                  <div key={st.id} className={"step-row " + cls}>
                    <span className="step-mark"></span>
                    <div className="step-text">
                      {st.cap}
                      <small>{st.detail}</small>
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        </aside>

        {/* RIGHT — fake browser */}
        <div className="sim-stage-v2">
          <div className="browser-shell">
            <div className="url-row">
              <div className="nav-btns">
                <button className="btn-circ">{Ico.back}</button>
                <button className="btn-circ" style={{transform:"rotate(180deg)"}}>{Ico.back}</button>
                <button className="btn-circ"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M21 12 a9 9 0 1 1-3-6.7 L21 8"/><path d="M21 3 v5 h-5"/></svg></button>
              </div>
              <div className="url-pill">
                <span className="lock">🔒</span>
                <span>{platform.url}</span>
              </div>
              <span className="profile-pill">Profile: <b>{platform.profile}</b></span>
            </div>
            <div className="browser-canvas" style={{width: "100%", maxWidth: 760, alignSelf: "stretch"}}>
              <FlowPage s={flowState} typed={typed}/>
              <AICursor x={coords.x} y={coords.y + 60} label="Hand Hub" ripple={rippleKey}/>
            </div>
          </div>
          <div className="sim-caption-v2">
            <span className="step-pill">STEP {String(stepIdx+1).padStart(2,"0")}/{String(STEPS.length).padStart(2,"0")}</span>
            <span className="step-action">{STEPS[stepIdx].cap}</span>
            <div className="step-detail">
              <span>{STEPS[stepIdx].detail}</span>
              <button className="ctrl-btn" onClick={() => setPaused(p => !p)}>{paused ? "▸ Tiếp tục" : "⏸ Tạm dừng"}</button>
              <button className="ctrl-btn" onClick={() => { setStepIdx(0); setTyped(0); setActiveJob(0); setState({menu:false,type:"video",mode:"frame",aspect:"16:9",dur:"8s",focus:false,typing:false,armed:false,thumb:0,platform:"veo3"}); }}>↺ Reset</button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

window.Simulation = Simulation;
