/* global React */
const { useState: useTweaksState, useEffect: useTweaksEffect } = React;

function Tweaks({ variant, setVariant }) {
  const [active, setActive] = useTweaksState(false);

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

  if (!active) return null;

  const opts = [
    { id: "photo", label: "Photo" },
    { id: "editorial", label: "Editorial" },
    { id: "center", label: "Centered" },
    { id: "split", label: "Split" },
  ];

  const pick = (id) => {
    setVariant(id);
    window.parent.postMessage({ type: "__edit_mode_set_keys", edits: { heroVariant: id } }, "*");
  };

  return (
    <div className="tweaks">
      <div className="t-title">
        <span>Tweaks</span>
        <span style={{color: "var(--muted)", fontSize: 9}}>AIS</span>
      </div>
      <div className="t-group">
        <div className="t-label">Hero Layout</div>
        <div className="t-opts">
          {opts.map((o) => (
            <button
              key={o.id}
              className={`t-opt ${variant === o.id ? "active" : ""}`}
              onClick={() => pick(o.id)}
            >
              {o.label}
            </button>
          ))}
        </div>
      </div>
    </div>
  );
}
window.Tweaks = Tweaks;
