/* portfolio-tweaks-panel-app.jsx — v5 Tweaks panel
   Surface: accent color, font pairing, density, hero variant,
   product card style, resume variant, section visibility.

   Reads & writes data.settings via the host `update` callback so changes
   persist to localStorage (same store as admin CMS).
*/

const { useState: useStateT, useEffect: useEffectT } = React;

const TweaksPortfolio = ({ data, update }) => {
  const settings = data.settings || {};
  const [open, setOpen] = useStateT(false);

  // EditMode host wiring (toolbar toggle)
  useEffectT(() => {
    const onMsg = (e) => {
      if (!e?.data || typeof e.data !== "object") return;
      if (e.data.type === "__activate_edit_mode") setOpen(true);
      if (e.data.type === "__deactivate_edit_mode") setOpen(false);
    };
    window.addEventListener("message", onMsg);
    // tell host we're available
    try { window.parent.postMessage({ type: "__edit_mode_available" }, "*"); } catch {}
    return () => window.removeEventListener("message", onMsg);
  }, []);

  const close = () => {
    setOpen(false);
    try { window.parent.postMessage({ type: "__edit_mode_dismissed" }, "*"); } catch {}
  };

  const setSetting = (key, value) => {
    update({ ...data, settings: { ...settings, [key]: value } });
  };

  const setShow = (key, value) => {
    update({
      ...data,
      settings: {
        ...settings,
        showSections: { ...(settings.showSections || {}), [key]: value }
      }
    });
  };

  if (!open) return null;

  return (
    <div className="tweaks-panel-v5">
      <div className="tw-head">
        <div>
          <strong>Tweaks</strong>
          <span>Live design controls — saves automatically</span>
        </div>
        <button className="tw-close" onClick={close}><Icon name="close" size={14} /></button>
      </div>

      <div className="tw-body">

        <div className="tw-section">
          <div className="tw-lab">Theme</div>
          <div className="tw-segmented">
            {[
              { id: "light", label: "Light" },
              { id: "dark",  label: "Dark · Gold" }
            ].map(opt => (
              <button
                key={opt.id}
                className={"tw-seg-btn" + (settings.theme === opt.id ? " active" : "")}
                onClick={() => setSetting("theme", opt.id)}
              >{opt.label}</button>
            ))}
          </div>
        </div>

        <div className="tw-section">
          <div className="tw-lab">Accent</div>
          <div className="tw-swatch-row">
            {[
              { id: "navy",    color: "#1e3a8a", label: "Navy" },
              { id: "gold",    color: "#b45309", label: "Gold" },
              { id: "emerald", color: "#0d9488", label: "Emerald" },
              { id: "violet",  color: "#7c3aed", label: "Violet" }
            ].map(opt => (
              <button
                key={opt.id}
                className={"tw-swatch" + (settings.accent === opt.id ? " active" : "")}
                style={{ background: opt.color }}
                onClick={() => setSetting("accent", opt.id)}
                title={opt.label}
              ><span className="tw-sw-label">{opt.label}</span></button>
            ))}
          </div>
        </div>

        <div className="tw-section">
          <div className="tw-lab">Font pairing</div>
          <div className="tw-list">
            {[
              { id: "inter-instrument", label: "Inter + Instrument Serif", note: "Current — clean / editorial" },
              { id: "geist-playfair",   label: "Geist + Playfair",         note: "Modern / luxurious" },
              { id: "system-georgia",   label: "System + Georgia",          note: "Newspaper / classic" }
            ].map(opt => (
              <button
                key={opt.id}
                className={"tw-list-btn" + (settings.fontPair === opt.id ? " active" : "")}
                onClick={() => setSetting("fontPair", opt.id)}
              >
                <strong>{opt.label}</strong>
                <span>{opt.note}</span>
              </button>
            ))}
          </div>
        </div>

        <div className="tw-section">
          <div className="tw-lab">Density</div>
          <div className="tw-segmented">
            {[
              { id: "comfortable", label: "Comfortable" },
              { id: "compact",     label: "Compact" }
            ].map(opt => (
              <button
                key={opt.id}
                className={"tw-seg-btn" + (settings.density === opt.id ? " active" : "")}
                onClick={() => setSetting("density", opt.id)}
              >{opt.label}</button>
            ))}
          </div>
        </div>

        <div className="tw-section">
          <div className="tw-lab">Hero variant</div>
          <div className="tw-segmented">
            {[
              { id: "split",    label: "Split" },
              { id: "left",     label: "Left text" },
              { id: "centered", label: "Centered" }
            ].map(opt => (
              <button
                key={opt.id}
                className={"tw-seg-btn" + (settings.heroVariant === opt.id ? " active" : "")}
                onClick={() => setSetting("heroVariant", opt.id)}
              >{opt.label}</button>
            ))}
          </div>
        </div>

        <div className="tw-section">
          <div className="tw-lab">Product card style</div>
          <div className="tw-segmented">
            {[
              { id: "grid",   label: "Grid" },
              { id: "list",   label: "List" },
              { id: "mosaic", label: "Mosaic" }
            ].map(opt => (
              <button
                key={opt.id}
                className={"tw-seg-btn" + (settings.productCardStyle === opt.id ? " active" : "")}
                onClick={() => setSetting("productCardStyle", opt.id)}
              >{opt.label}</button>
            ))}
          </div>
        </div>

        <div className="tw-section">
          <div className="tw-lab">Resume variant (active)</div>
          <div className="tw-list">
            {(data.resumeEngine?.variants || []).map(v => (
              <button
                key={v.id}
                className={"tw-list-btn" + (settings.resumeVariant === v.id ? " active" : "")}
                onClick={() => setSetting("resumeVariant", v.id)}
              >
                <strong>{v.name}</strong>
                <span>{v.kicker}</span>
              </button>
            ))}
          </div>
        </div>

        <div className="tw-section">
          <div className="tw-lab">Section visibility</div>
          <div className="tw-toggles">
            {[
              ["capabilities", "Signature Identity"],
              ["process",      "How I Build"],
              ["principles",   "Principles"],
              ["products",     "Product Ecosystem"],
              ["frameworks",   "Frameworks"],
              ["learning",     "Learning Portal"],
              ["showcase",     "App Showcase"],
              ["stack",        "Tech Stack"],
              ["cases",        "Case Studies"],
              ["downloads",    "Downloads"],
              ["social",       "Social Studio"],
              ["evolution",    "Engineering Evolution"],
              ["journey",      "Journey"],
              ["resumeEngine", "Resume Engine"],
              ["contact",      "Contact"]
            ].map(([key, label]) => {
              const on = settings.showSections?.[key] !== false;
              return (
                <button
                  key={key}
                  className={"tw-toggle" + (on ? " on" : "")}
                  onClick={() => setShow(key, !on)}
                >
                  <span className="tw-tg-track"><span className="tw-tg-knob"></span></span>
                  <span>{label}</span>
                </button>
              );
            })}
          </div>
        </div>

      </div>

      <div className="tw-foot">
        <span>v5 · live tweaks</span>
        <button className="tw-reset" onClick={() => {
          if (!confirm("Reset all tweaks to defaults?")) return;
          update({
            ...data,
            settings: {
              ...settings,
              theme: "light",
              accent: "navy",
              fontPair: "inter-instrument",
              density: "comfortable",
              heroVariant: "split",
              productCardStyle: "grid",
              resumeVariant: "product-eng"
            }
          });
        }}>Reset tweaks</button>
      </div>
    </div>
  );
};

Object.assign(window, { TweaksPortfolio });
