/* ============ Interactive Demo — working click-through app ============ */

/* ---- MachiLog sample app screens (rendered HTML mockups) ---- */
function ApStatusbar({ dark }) {
  return (
    <div className={`ap-status ${dark ? "d" : ""}`}>
      <span className="mono">9:41</span>
      <span className="ap-notch"></span>
      <span className="ap-status-r mono">●●● ▮</span>
    </div>
  );
}

function Sc_Home() {
  return (
    <div className="ap ap-home">
      <ApStatusbar />
      <div className="ap-top">
        <div>
          <div className="ap-hello mono">KAMIYAMA — 神領エリア</div>
          <div className="ap-title">おはようございます</div>
        </div>
        <div className="ap-avatar"></div>
      </div>
      <div className="ap-summary">
        <div className="ap-sum-card">
          <span className="mono">対応中</span>
          <strong>3<small>件</small></strong>
        </div>
        <div className="ap-sum-card">
          <span className="mono">今月の記録</span>
          <strong>28<small>件</small></strong>
        </div>
        <div className="ap-sum-card accent">
          <span className="mono">センサー異常</span>
          <strong>1<small>件</small></strong>
        </div>
      </div>
      <div className="ap-sec-row"><span>近くの記録</span><span className="mono">MAP ↗</span></div>
      <div className="ap-list">
        {[["道路の陥没","神領 大埜地","対応中"],["街灯の故障","下分 中央","受付"],["見守り要請","阿野 西","完了"]].map((r,i)=>(
          <div className="ap-item" key={i}>
            <span className={`ap-pin k${i}`}></span>
            <div className="ap-item-b"><strong>{r[0]}</strong><span className="mono">{r[1]}</span></div>
            <span className={`ap-chip s${i}`}>{r[2]}</span>
          </div>
        ))}
      </div>
      <div className="ap-fab">＋ 記録する</div>
      <ApTabbar active={0} />
    </div>
  );
}

function Sc_Map() {
  return (
    <div className="ap ap-map">
      <ApStatusbar />
      <div className="ap-map-canvas dotgrid">
        <div className="ap-map-roads"></div>
        {[[28,34,0],[58,22,1],[44,60,2],[72,52,0],[36,76,1]].map((p,i)=>(
          <span key={i} className={`ap-map-pin k${p[2]}`} style={{left:p[0]+"%",top:p[1]+"%"}}></span>
        ))}
        <div className="ap-map-head">
          <span className="ap-back">←</span>
          <span className="ap-map-title">マップ</span>
          <span className="mono">5件</span>
        </div>
      </div>
      <div className="ap-map-card">
        <div className="ap-pin k0"></div>
        <div className="ap-item-b"><strong>道路の陥没</strong><span className="mono">神領 大埜地 · 120m</span></div>
        <span className="ap-chip s0">対応中</span>
      </div>
      <ApTabbar active={1} />
    </div>
  );
}

function Sc_Report() {
  const cats = [["🛣","道路・舗装"],["💡","街灯・照明"],["🌿","公園・緑地"],["🚸","見守り"],["📡","センサー"],["⋯","その他"]];
  return (
    <div className="ap ap-report">
      <ApStatusbar />
      <div className="ap-form-head"><span className="ap-back">←</span><span className="ap-map-title">記録する</span><span></span></div>
      <div className="ap-form-lead">どんな気づきですか？<span className="mono">SELECT CATEGORY</span></div>
      <div className="ap-cat-grid">
        {cats.map((c,i)=>(
          <div className={`ap-cat ${i===0?"sel":""}`} key={i}><span className="ap-cat-i">{c[0]}</span><span>{c[1]}</span></div>
        ))}
      </div>
      <div className="ap-photo">
        <div className="ap-photo-box"><span className="mono">＋ 写真を追加</span></div>
      </div>
      <div className="ap-next">次へ進む →</div>
    </div>
  );
}

function Sc_Confirm() {
  return (
    <div className="ap ap-confirm">
      <ApStatusbar />
      <div className="ap-form-head"><span className="ap-back">←</span><span className="ap-map-title">確認</span><span></span></div>
      <div className="ap-conf-img dotgrid"><span className="mono">PHOTO</span></div>
      <div className="ap-conf-rows">
        {[["カテゴリー","道路・舗装"],["場所","神領 大埜地 299-1 付近"],["内容","歩道が陥没している。通行注意。"],["記録者","あなた"]].map((r,i)=>(
          <div className="ap-conf-row" key={i}><span className="mono">{r[0]}</span><strong>{r[1]}</strong></div>
        ))}
      </div>
      <div className="ap-submit">この内容で送信する</div>
    </div>
  );
}

function Sc_Done() {
  return (
    <div className="ap ap-done">
      <ApStatusbar />
      <div className="ap-done-c">
        <div className="ap-check"><svg viewBox="0 0 48 48"><path d="M14 25l7 7 14-15" fill="none" stroke="currentColor" strokeWidth="3.4" strokeLinecap="round" strokeLinejoin="round"/></svg></div>
        <h3>記録を送信しました</h3>
        <p>あなたの気づきが、まちの記録になりました。<br/>担当者が確認し、対応状況をお知らせします。</p>
        <div className="ap-done-id mono">REPORT #2025-0418</div>
        <div className="ap-home-btn">ホームに戻る</div>
      </div>
    </div>
  );
}

function ApTabbar({ active }) {
  const tabs = [["⌂","ホーム"],["◎","マップ"],["＋",""],["🔔","通知"],["☰","メニュー"]];
  return (
    <div className="ap-tabbar">
      {tabs.map((t,i)=>(
        <span key={i} className={`ap-tab ${i===active?"on":""} ${i===2?"mid":""}`}>
          <i>{t[0]}</i>{t[1]&&<em>{t[1]}</em>}
        </span>
      ))}
    </div>
  );
}

const DEMO_SCREENS = {
  home:    { name: "ホーム", Comp: Sc_Home, hotspots: [
    { id:"h1", label:"記録する", x:6, y:84.5, w:88, h:7.2, target:"report", t:"slide-left", tip:"記録フローを開始" },
    { id:"h2", label:"マップを開く", x:60, y:53.5, w:34, h:5, target:"map", t:"slide-left", tip:"地図で見る" },
  ]},
  map:     { name: "マップ", Comp: Sc_Map, hotspots: [
    { id:"m1", label:"戻る", x:4, y:5.5, w:16, h:5.5, target:"home", t:"slide-right", tip:"ホームへ" },
    { id:"m2", label:"記録を開く", x:5, y:80, w:90, h:9, target:"confirm", t:"slide-left", tip:"この記録の詳細" },
  ]},
  report:  { name: "記録 / カテゴリー", Comp: Sc_Report, hotspots: [
    { id:"r0", label:"戻る", x:4, y:5.5, w:16, h:5.5, target:"home", t:"slide-right" },
    { id:"r1", label:"次へ", x:6, y:88, w:88, h:7, target:"confirm", t:"slide-left", tip:"確認画面へ" },
  ]},
  confirm: { name: "確認", Comp: Sc_Confirm, hotspots: [
    { id:"c0", label:"戻る", x:4, y:5.5, w:16, h:5.5, target:"report", t:"slide-right" },
    { id:"c1", label:"送信する", x:6, y:88, w:88, h:7, target:"done", t:"scale", tip:"送信を確定" },
  ]},
  done:    { name: "完了", Comp: Sc_Done, hotspots: [
    { id:"d1", label:"ホームに戻る", x:18, y:78, w:64, h:7, target:"home", t:"fade", tip:"最初の画面へ" },
  ]},
};

function GenericHotspotDemo({ config = {}, title = "Interactive Demo" }) {
  const screens = config.screens || [];
  const firstScreen = config.initial || (screens[0] && screens[0].id);
  const [screen, setScreen] = useState(firstScreen);
  const [hist, setHist] = useState([]);
  const [showSpots, setShowSpots] = useState(false);
  const [hint, setHint] = useState(true);
  const [full, setFull] = useState(false);

  useEffect(() => { const t = setTimeout(() => setHint(false), 3200); return () => clearTimeout(t); }, [screen]);
  useEffect(() => {
    if (!full) return;
    const onKey = (e) => { if (e.key === "Escape") setFull(false); };
    window.addEventListener("keydown", onKey); return () => window.removeEventListener("keydown", onKey);
  }, [full]);

  if (!screens.length) {
    return (
      <div className="demo">
        <div className="demo-shell">
          <div className="demo-stage dotgrid"><Placeholder label="DEMO CONFIG REQUIRED" k={1} /></div>
        </div>
      </div>
    );
  }

  const cur = screens.find(s => s.id === screen) || screens[0];
  const navigate = (target) => {
    if (!target || !screens.some(s => s.id === target)) return;
    setHist(h => [...h, cur.id]);
    setScreen(target);
    setHint(false);
  };
  const back = () => {
    if (!hist.length) return;
    const prev = hist[hist.length - 1];
    setHist(h => h.slice(0, -1));
    setScreen(prev);
  };
  const reset = () => { setHist([]); setScreen(firstScreen); setHint(true); };

  return (
    <div className={`demo ${full ? "full" : ""}`}>
      {full && <div className="demo-fs-bg" onClick={() => setFull(false)}></div>}
      <div className="demo-shell">
        <div className="demo-toolbar">
          <div className="demo-tb-l">
            <span className="demo-live mono"><i></i>INTERACTIVE DEMO</span>
            <span className="demo-screen-name">{cur.name || title}</span>
          </div>
          <div className="demo-tb-r">
            <button className="demo-ic" onClick={back} disabled={!hist.length} title="戻る">←</button>
            <button className="demo-ic" onClick={reset} title="最初から">⟳</button>
            <button className={`demo-ic ${showSpots ? "on" : ""}`} onClick={() => setShowSpots(s => !s)} title="操作できる場所を表示">◎</button>
            <button className="demo-ic" onClick={() => setFull(f => !f)} title="フルスクリーン">{full ? "×" : "⤢"}</button>
          </div>
        </div>
        <div className="demo-stage dotgrid">
          <div className={`demo-image-device ${config.device || "phone"}`}>
            <div className={`demo-image-screen ${cur.image ? "has-image" : ""}`}>
              {cur.image
                ? <img src={cur.image} alt={cur.name || title} />
                : <Placeholder label={(cur.name || title).toUpperCase()} k={0} />}
              <div className="demo-hotspots">
                {(cur.hotspots || []).map(h => (
                  <button key={h.id || h.label}
                    className={`hotspot ${showSpots ? "show" : ""} ${hint ? "hint" : ""}`}
                    style={{ left: h.x + "%", top: h.y + "%", width: h.w + "%", height: h.h + "%" }}
                    title={h.tip || h.label}
                    onClick={() => navigate(h.target)}>
                    {(h.tip || h.label) && <span className="hotspot-tip mono">{h.tip || h.label}</span>}
                  </button>
                ))}
              </div>
            </div>
          </div>
        </div>
        <div className="demo-hintbar mono">
          <span>{showSpots ? "ハイライト中 — タップで画面遷移します" : "画面をタップして操作できます。◎ で操作箇所を表示。"}</span>
          <span className="demo-count">{screens.length} SCREENS</span>
        </div>
      </div>
    </div>
  );
}

function InteractiveDemo({ initial = "home", config, title }) {
  if (config && (config.type === "imageHotspots" || config.type === "flow")) {
    return <GenericHotspotDemo config={config} title={title} />;
  }
  const [screen, setScreen] = useState(initial);
  const [hist, setHist] = useState([]);
  const [anim, setAnim] = useState("");
  const [showSpots, setShowSpots] = useState(false);
  const [hint, setHint] = useState(true);
  const [device, setDevice] = useState("phone");
  const [full, setFull] = useState(false);
  const stageRef = useRef(null);

  useEffect(() => { const t = setTimeout(() => setHint(false), 3200); return () => clearTimeout(t); }, [screen]);
  useEffect(() => {
    if (!full) return;
    const onKey = (e) => { if (e.key === "Escape") setFull(false); };
    window.addEventListener("keydown", onKey); return () => window.removeEventListener("keydown", onKey);
  }, [full]);

  const navigate = (target, t) => {
    setHist(h => [...h, screen]);
    setAnim(t || "fade"); setScreen(target); setHint(false);
  };
  const back = () => {
    if (!hist.length) return;
    const prev = hist[hist.length - 1];
    setHist(h => h.slice(0, -1)); setAnim("slide-right"); setScreen(prev);
  };
  const reset = () => { setHist([]); setAnim("fade"); setScreen(initial); setHint(true); };

  const cur = DEMO_SCREENS[screen];
  const Comp = cur.Comp;

  const frame = (
    <div className={`demo-device ${device}`}>
      {device === "desktop" && <div className="demo-browserbar"><i></i><i></i><i></i><span className="mono">machilog.app</span></div>}
      <div className="demo-screen-clip">
        <div key={screen} className={`demo-screen anim-${anim}`} ref={stageRef}>
          <Comp />
          <div className="demo-hotspots">
            {cur.hotspots.map(h => (
              <button key={h.id}
                className={`hotspot ${showSpots ? "show" : ""} ${hint ? "hint" : ""}`}
                style={{ left: h.x + "%", top: h.y + "%", width: h.w + "%", height: h.h + "%" }}
                title={h.tip || h.label}
                onClick={() => navigate(h.target, h.t)}>
                {h.tip && <span className="hotspot-tip mono">{h.tip}</span>}
              </button>
            ))}
          </div>
        </div>
      </div>
    </div>
  );

  return (
    <div className={`demo ${full ? "full" : ""}`}>
      {full && <div className="demo-fs-bg" onClick={() => setFull(false)}></div>}
      <div className="demo-shell">
        <div className="demo-toolbar">
          <div className="demo-tb-l">
            <span className="demo-live mono"><i></i>INTERACTIVE DEMO</span>
            <span className="demo-screen-name">{cur.name}</span>
          </div>
          <div className="demo-tb-r">
            <button className="demo-ic" onClick={back} disabled={!hist.length} title="戻る">←</button>
            <button className="demo-ic" onClick={reset} title="最初から">⟳</button>
            <button className={`demo-ic ${showSpots ? "on" : ""}`} onClick={() => setShowSpots(s => !s)} title="操作できる場所を表示">◎</button>
            <div className="demo-seg">
              <button className={device === "phone" ? "on" : ""} onClick={() => setDevice("phone")}>Phone</button>
              <button className={device === "desktop" ? "on" : ""} onClick={() => setDevice("desktop")}>PC</button>
            </div>
            <button className="demo-ic" onClick={() => setFull(f => !f)} title="フルスクリーン">{full ? "×" : "⤢"}</button>
          </div>
        </div>
        <div className="demo-stage dotgrid">
          {frame}
        </div>
        <div className="demo-hintbar mono">
          <span>{showSpots ? "ハイライト中 — タップで画面遷移します" : "画面をタップして操作できます。◎ で操作箇所を表示。"}</span>
          <span className="demo-count">{Object.keys(DEMO_SCREENS).length} SCREENS</span>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { InteractiveDemo, GenericHotspotDemo, DEMO_SCREENS });
