// Tweaks panel: aligned to new config shape (lots array, titleFont).

function TweaksPanel({ config, setConfig, tweakDefaults }) {
  const [active, setActive] = React.useState(false);
  const [open, setOpen] = React.useState(true);

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

  if (!active) return null;

  const update = (patch) => {
    const next = { ...config, ...patch };
    setConfig(next);
    const keys = {};
    for (const k of Object.keys(patch)) keys[k] = next[k];
    window.parent.postMessage({ type: '__edit_mode_set_keys', edits: keys }, '*');
  };

  const updateLot = (idx, field, value) => {
    const lots = config.lots.map((l, i) =>
      i === idx ? { ...l, [field]: field === 'preco' ? (Number(value) || 0) : value } : l
    );
    update({ lots });
  };

  const addLot = () => {
    const last = config.lots[config.lots.length - 1];
    const newStart = last ? last.fim : '2026-04-20T00:00:00';
    update({
      lots: [...config.lots, {
        ini: newStart,
        fim: newStart,
        preco: last ? last.preco + 10 : 19,
      }]
    });
  };
  const removeLot = () => {
    if (config.lots.length > 1) update({ lots: config.lots.slice(0, -1) });
  };

  return (
    <div className={`tweaks ${open ? 'open' : 'closed'}`}>
      <div className="tweaks-head">
        <span className="mono">// TWEAKS</span>
        <button className="tweaks-toggle" onClick={() => setOpen(o => !o)}>{open ? '–' : '+'}</button>
      </div>
      {open && (
        <div className="tweaks-body">
          <div className="tweaks-row">
            <label className="mono">simular data</label>
            <input
              type="date"
              value={config.simulatedDate || ''}
              onChange={(e) => update({ simulatedDate: e.target.value })}
            />
            <button
              className="tweaks-btn mono"
              onClick={() => update({ simulatedDate: '' })}
            >real</button>
          </div>

          <div className="tweaks-row">
            <label className="mono">datas evento</label>
            <input
              type="text"
              value={config.eventDates}
              onChange={(e) => update({ eventDates: e.target.value })}
            />
          </div>

          <div className="tweaks-row">
            <label className="mono">fonte do título</label>
            <select
              value={config.titleFont}
              onChange={(e) => update({ titleFont: e.target.value })}
            >
              <option>Space Grotesk</option>
              <option>Fraunces</option>
              <option>Inter</option>
              <option>JetBrains Mono</option>
              <option>Playfair Display</option>
            </select>
          </div>

          <div className="tweaks-row">
            <label className="mono">peça de cristal</label>
            <select
              value={config.crystal || '1'}
              onChange={(e) => update({ crystal: e.target.value })}
            >
              <option value="1">cristal 01 — facetado</option>
              <option value="2">cristal 02 — liso</option>
              <option value="none">nenhum</option>
            </select>
          </div>

          <div className="tweaks-row">
            <label className="mono">URL checkout</label>
            <input
              type="text"
              value={config.checkoutUrl}
              onChange={(e) => update({ checkoutUrl: e.target.value })}
            />
          </div>

          <div className="tweaks-row col">
            <label className="mono">lotes (ini · fim · R$)</label>
            <div className="tweaks-lots">
              {config.lots.map((L, i) => (
                <div className="tweaks-lot" key={i}>
                  <span className="mono">L{String(i + 1).padStart(2, '0')}</span>
                  <input
                    type="datetime-local"
                    value={L.ini}
                    onChange={(e) => updateLot(i, 'ini', e.target.value)}
                  />
                  <input
                    type="datetime-local"
                    value={L.fim}
                    onChange={(e) => updateLot(i, 'fim', e.target.value)}
                  />
                  <input
                    type="number"
                    step="1"
                    value={L.preco}
                    onChange={(e) => updateLot(i, 'preco', e.target.value)}
                  />
                </div>
              ))}
              <div className="tweaks-row" style={{ gap: 8 }}>
                <button className="tweaks-btn mono" onClick={addLot}>+ lote</button>
                {config.lots.length > 1 &&
                  <button className="tweaks-btn mono" onClick={removeLot}>– lote</button>}
              </div>
            </div>
          </div>

          <div className="tweaks-row">
            <label className="mono">reset</label>
            <button
              className="tweaks-btn mono"
              onClick={() => update(tweakDefaults)}
            >restaurar padrão</button>
          </div>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { TweaksPanel });
