/* global React, ReactDOM */
(function() {
const { useState: useStateApp } = React;
const { useRoute, Home, ScalesList, ScaleCompile, Report } = window.RT;

const TWEAK_DEFAULTS = {
  "homeVariant": "editorial",
  "listVariant": "table"
};

function App() {
  const route = useRoute();
  const [tweaks, setTweaks] = useStateApp(TWEAK_DEFAULTS);
  const [tweakOpen, setTweakOpen] = useStateApp(false);

  React.useEffect(() => {
    const handler = (e) => {
      if (!e.data || !e.data.type) return;
      if (e.data.type === "__activate_edit_mode") setTweakOpen(true);
      if (e.data.type === "__deactivate_edit_mode") setTweakOpen(false);
    };
    window.addEventListener("message", handler);
    window.parent.postMessage({ type: "__edit_mode_available" }, "*");
    return () => window.removeEventListener("message", handler);
  }, []);

  const setTweak = (key, value) => {
    setTweaks(prev => {
      const next = { ...prev, [key]: value };
      window.parent.postMessage({ type: "__edit_mode_set_keys", edits: { [key]: value } }, "*");
      return next;
    });
  };

  let view;
  if (route.length === 0) {
    view = <Home variant={tweaks.homeVariant} />;
  } else if (route[0] === "scales") {
    view = <ScalesList variant={tweaks.listVariant} />;
  } else if (route[0] === "scale" && route[1]) {
    if (route[2] === "report") {
      view = <Report scaleId={route[1]} />;
    } else {
      view = <ScaleCompile scaleId={route[1]} />;
    }
  } else {
    view = <Home variant={tweaks.homeVariant} />;
  }

  return (
    <div className="rt-app">
      {view}
      {tweakOpen && (
        <TweaksUI tweaks={tweaks} setTweak={setTweak} onClose={() => {
          setTweakOpen(false);
          window.parent.postMessage({ type: "__edit_mode_dismissed" }, "*");
        }} />
      )}
    </div>
  );
}

function TweaksUI({ tweaks, setTweak, onClose }) {
  return (
    <div className="rt-no-print" style={{
      position: "fixed", bottom: 24, right: 24, width: 280,
      background: "#fff", border: "1px solid var(--rt-line)",
      borderRadius: "var(--rt-r-lg)", boxShadow: "var(--rt-shadow-lg)",
      zIndex: 100, fontSize: 13,
    }}>
      <div style={{ padding: "14px 16px", borderBottom: "1px solid var(--rt-line-2)", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
        <div style={{ fontFamily: "var(--rt-serif)", fontSize: 16, fontWeight: 600, color: "var(--rt-navy-900)" }}>Tweaks</div>
        <button onClick={onClose} style={{ background: "transparent", border: "none", color: "var(--rt-muted)", fontSize: 18, cursor: "pointer", padding: 0, width: 24, height: 24 }}>×</button>
      </div>
      <div style={{ padding: 16, display: "flex", flexDirection: "column", gap: 18 }}>
        <TweakSeg
          label="Variante home"
          options={[
            { v: "editorial", l: "Editoriale" },
            { v: "panel",     l: "Pannello scuro" },
          ]}
          value={tweaks.homeVariant}
          onChange={(v) => setTweak("homeVariant", v)}
        />
        <TweakSeg
          label="Layout lista scale"
          options={[
            { v: "table", l: "Tabella" },
            { v: "grid",  l: "Card" },
          ]}
          value={tweaks.listVariant}
          onChange={(v) => setTweak("listVariant", v)}
        />
        <div style={{ borderTop: "1px solid var(--rt-line-2)", paddingTop: 14, fontSize: 11, color: "var(--rt-muted)", lineHeight: 1.5 }}>
          Le varianti sono toggle live: cambia mentre visualizzi la pagina interessata.
        </div>
      </div>
    </div>
  );
}

function TweakSeg({ label, options, value, onChange }) {
  return (
    <div>
      <div style={{ fontSize: 11, fontWeight: 500, color: "var(--rt-muted)", textTransform: "uppercase", letterSpacing: ".06em", marginBottom: 6 }}>{label}</div>
      <div style={{ display: "flex", padding: 3, background: "var(--rt-navy-50)", borderRadius: "var(--rt-r)", gap: 2 }}>
        {options.map(o => (
          <button key={o.v} onClick={() => onChange(o.v)} style={{
            flex: 1, border: "none",
            background: value === o.v ? "#fff" : "transparent",
            color: value === o.v ? "var(--rt-navy-900)" : "var(--rt-muted)",
            padding: "6px 10px",
            borderRadius: "var(--rt-r-sm)",
            fontSize: 12, fontWeight: 500, cursor: "pointer",
            boxShadow: value === o.v ? "var(--rt-shadow-sm)" : "none",
          }}>{o.l}</button>
        ))}
      </div>
    </div>
  );
}

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