/* global React, ReactDOM, window, useTweaks, TweaksPanel, TweakSection, TweakSlider, TweakToggle, TweakRadio */
// ============================================================
// APP ROOT — language, sound, shell, tweaks
// ============================================================

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "turnMs": 900,
  "sound": false,
  "cover": "embossed"
}/*EDITMODE-END*/;

// ---- page-turn sound (synthesised paper flutter, no asset) ----
let _audio = null;
function playTurn() {
  try {
    _audio = _audio || new (window.AudioContext || window.webkitAudioContext)();
    const ctx = _audio;
    if (ctx.state === "suspended") ctx.resume();
    const dur = 0.34;
    const buf = ctx.createBuffer(1, ctx.sampleRate * dur, ctx.sampleRate);
    const data = buf.getChannelData(0);
    for (let i = 0; i < data.length; i++) {
      const t = i / data.length;
      const env = Math.sin(Math.PI * t) * (1 - t) * (0.5 + 0.5 * Math.sin(t * 60));
      data[i] = (Math.random() * 2 - 1) * env * 0.5;
    }
    const src = ctx.createBufferSource(); src.buffer = buf;
    const bp = ctx.createBiquadFilter(); bp.type = "bandpass"; bp.frequency.value = 2600; bp.Q.value = 0.6;
    const g = ctx.createGain(); g.gain.value = 0.5;
    src.connect(bp); bp.connect(g); g.connect(ctx.destination);
    src.start();
  } catch (e) { /* no-op */ }
}

function App() {
  const { T, Book, CatWalker } = window;
  const [tw, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [lang, setLang] = React.useState("en");
  const t = T[lang];

  React.useEffect(() => {
    document.documentElement.lang = lang;
    document.documentElement.dir = t.dir;
  }, [lang]);

  return (
    <React.Fragment>
      <div className="shell">
        <div className="shell-title"><span className="dot" />{t.fieldBook}</div>
        <div className="shell-tools">
          <button className={"pill" + (tw.sound ? " on" : "")} onClick={() => setTweak("sound", !tw.sound)}
            title="page-turn sound">
            {tw.sound ? "♪" : "♪̸"} <span style={{ opacity: .7 }}>{lang === "ar" ? "صوت" : "sound"}</span>
          </button>
          <div className="lang-toggle">
            <button className={lang === "en" ? "active" : ""} onClick={() => setLang("en")}>EN</button>
            <button className={lang === "ar" ? "active" : ""} onClick={() => setLang("ar")}>ع</button>
          </div>
        </div>
      </div>

      <Book lang={lang} setLang={setLang} t={t} turnMs={tw.turnMs} sound={tw.sound}
        coverStyle={tw.cover} playTurn={playTurn} />

      <CatWalker />

      <TweaksPanel>
        <TweakSection label={lang === "ar" ? "قلب الصفحة" : "Page turn"} />
        <TweakSlider label={lang === "ar" ? "سرعة القلب" : "Turn speed"} value={tw.turnMs}
          min={400} max={1600} step={50} unit="ms" onChange={(v) => setTweak("turnMs", v)} />
        <TweakToggle label={lang === "ar" ? "صوت الورق" : "Paper sound"} value={tw.sound}
          onChange={(v) => setTweak("sound", v)} />
        <TweakSection label={lang === "ar" ? "الغلاف" : "Cover treatment"} />
        <TweakRadio label={lang === "ar" ? "التصميم" : "Style"} value={tw.cover}
          options={["embossed", "minimal", "stamp"]} onChange={(v) => setTweak("cover", v)} />
      </TweaksPanel>
    </React.Fragment>
  );
}

ReactDOM.createRoot(document.getElementById("app")).render(<App />);
