/* Tweaks panel */
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "modulesVariant": "v1",
  "accentHue": 200,
  "fontDisplay": "Geist",
  "showROI": true,
  "showIntegrations": false,
  "showVideoTestimonials": true,
  "heroCopy": "Reservas, fila, delivery, fichas e WhatsApp. Tudo em um só painel."
}/*EDITMODE-END*/;

const TweaksContext = React.createContext(TWEAK_DEFAULTS);

function useTweaks() { return React.useContext(TweaksContext); }

const TweaksPanel = ({ tweaks, setTweaks }) => {
  const [visible, setVisible] = React.useState(false);
  const [min, setMin] = React.useState(false);

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

  const update = (k, v) => {
    const next = {...tweaks, [k]: v};
    setTweaks(next);
    window.parent.postMessage({type:'__edit_mode_set_keys', edits:{[k]: v}}, '*');
  };

  if (!visible) return null;

  return (
    <div className="fixed bottom-5 right-5 z-50 w-[340px] rounded-2xl bg-white/95 tweaks-panel shadow-[0_30px_80px_-20px_rgba(0,0,0,.3)] ring-1 ring-ink-200 overflow-hidden">
      <div className="px-4 py-3 flex items-center justify-between border-b border-ink-100 bg-gradient-to-r from-brand-50 to-white">
        <div className="flex items-center gap-2">
          <div className="w-6 h-6 rounded bg-brand-500 flex items-center justify-center">
            <span className="text-white text-[11px]">✦</span>
          </div>
          <span className="text-[12px] font-bold text-ink-900 uppercase tracking-[0.14em]">Tweaks</span>
        </div>
        <button onClick={()=>setMin(!min)} className="text-ink-400 hover:text-ink-900 text-[11px] mono">
          {min ? '▼' : '▲'}
        </button>
      </div>

      {!min && (
        <div className="p-4 space-y-4 max-h-[70vh] overflow-y-auto">
          {/* Modules variant */}
          <div>
            <label className="text-[10px] font-bold text-ink-500 uppercase tracking-[0.14em] mb-2 block">Variação de módulos</label>
            <div className="grid grid-cols-3 gap-1.5">
              {[
                {v:'v1',l:'Explorer',d:'Abas interativas'},
                {v:'v2',l:'Dashboard',d:'Grid denso'},
                {v:'v3',l:'Editorial',d:'Full-bleed'},
              ].map(o => (
                <button key={o.v} onClick={()=>update('modulesVariant', o.v)}
                        className={`p-2 rounded-lg text-left transition-all ${
                          tweaks.modulesVariant === o.v
                            ? 'bg-ink-900 text-white ring-2 ring-brand-500'
                            : 'bg-ink-50 hover:bg-ink-100 text-ink-800'
                        }`}>
                  <div className="text-[11px] font-bold">{o.l}</div>
                  <div className={`text-[9px] mt-0.5 ${tweaks.modulesVariant === o.v ? 'text-white/60' : 'text-ink-400'}`}>{o.d}</div>
                </button>
              ))}
            </div>
          </div>

          {/* Accent hue */}
          <div>
            <div className="flex justify-between items-baseline mb-2">
              <label className="text-[10px] font-bold text-ink-500 uppercase tracking-[0.14em]">Matiz do accent</label>
              <span className="mono text-[10px] text-brand-600 font-bold">{tweaks.accentHue}°</span>
            </div>
            <input type="range" min="0" max="360" step="5" value={tweaks.accentHue}
                   onChange={e => update('accentHue', +e.target.value)}
                   className="w-full cursor-pointer"
                   style={{background: 'linear-gradient(to right, hsl(0 90% 55%), hsl(60 90% 55%), hsl(120 90% 55%), hsl(180 90% 55%), hsl(240 90% 55%), hsl(300 90% 55%), hsl(360 90% 55%))', height:4, borderRadius:999}}/>
            <div className="flex gap-1.5 mt-2">
              {[200,220,160,30,340,280].map(h => (
                <button key={h} onClick={()=>update('accentHue', h)}
                        className={`w-6 h-6 rounded-full transition-transform hover:scale-110 ${tweaks.accentHue===h ? 'ring-2 ring-offset-2 ring-ink-900' : ''}`}
                        style={{background:`hsl(${h} 85% 52%)`}}/>
              ))}
            </div>
          </div>

          {/* Font */}
          <div>
            <label className="text-[10px] font-bold text-ink-500 uppercase tracking-[0.14em] mb-2 block">Fonte display</label>
            <div className="grid grid-cols-3 gap-1.5">
              {['Geist','Inter','Manrope'].map(f => (
                <button key={f} onClick={()=>update('fontDisplay', f)}
                        className={`p-2 rounded-lg text-[11px] font-bold transition-all ${
                          tweaks.fontDisplay === f
                            ? 'bg-ink-900 text-white'
                            : 'bg-ink-50 hover:bg-ink-100 text-ink-800'
                        }`}
                        style={{fontFamily:f}}>
                  {f}
                </button>
              ))}
            </div>
          </div>

          {/* Section toggles */}
          <div>
            <label className="text-[10px] font-bold text-ink-500 uppercase tracking-[0.14em] mb-2 block">Seções opcionais</label>
            <div className="space-y-1">
              {[
                {k:'showROI',l:'Calculadora de ROI'},
                {k:'showIntegrations',l:'Grid de integrações'},
                {k:'showVideoTestimonials',l:'Depoimentos em vídeo'},
              ].map(t => (
                <button key={t.k} onClick={()=>update(t.k, !tweaks[t.k])}
                        className="w-full flex items-center justify-between px-3 py-2 rounded-lg bg-ink-50 hover:bg-ink-100 transition-colors">
                  <span className="text-[12px] text-ink-800 font-medium">{t.l}</span>
                  <div className={`w-8 h-[18px] rounded-full transition-colors relative ${tweaks[t.k] ? 'bg-brand-500' : 'bg-ink-300'}`}>
                    <div className={`absolute top-0.5 w-[14px] h-[14px] rounded-full bg-white shadow transition-all ${tweaks[t.k] ? 'left-[16px]' : 'left-0.5'}`}></div>
                  </div>
                </button>
              ))}
            </div>
          </div>

          {/* Hero copy */}
          <div>
            <label className="text-[10px] font-bold text-ink-500 uppercase tracking-[0.14em] mb-2 block">Subtítulo do hero</label>
            <textarea value={tweaks.heroCopy} onChange={e=>update('heroCopy', e.target.value)}
                      rows="3"
                      className="w-full text-[12px] p-2.5 rounded-lg bg-ink-50 border border-ink-200 focus:border-brand-500 focus:ring-2 focus:ring-brand-100 outline-none resize-none"/>
          </div>

          <div className="pt-3 mt-3 border-t border-dashed border-ink-200 text-[10px] text-ink-400 text-center">
            Alternar variações sem recarregar
          </div>
        </div>
      )}
    </div>
  );
};

/* Apply hue and font to root */
const applyTweaks = (tweaks) => {
  const hue = tweaks.accentHue;
  const root = document.documentElement;
  // brand palette from hue (sky-blue is hue 200 by default)
  const baseHue = 200;
  const shift = hue - baseHue;
  root.style.setProperty('--brand-hue-shift', `${shift}deg`);
  // apply to custom property
  root.style.filter = '';
  // change accent via css variable assignment by rewriting tailwind? use simpler approach: set inline style on elements? We'll use a style override
  const styleId = 'tweak-styles';
  let el = document.getElementById(styleId);
  if (!el) { el = document.createElement('style'); el.id = styleId; document.head.appendChild(el); }
  const palette = {};
  [[50,97],[100,93],[200,85],[300,75],[400,62],[500,52],[600,44],[700,36],[800,28],[900,20]].forEach(([k,l]) => {
    palette[k] = `hsl(${hue} 85% ${l}%)`;
  });
  el.textContent = `
    :root { --brand-500: ${palette[500]}; }
    .bg-brand-50{background-color:${palette[50]}!important}
    .bg-brand-100{background-color:${palette[100]}!important}
    .bg-brand-400{background-color:${palette[400]}!important}
    .bg-brand-500{background-color:${palette[500]}!important}
    .bg-brand-600{background-color:${palette[600]}!important}
    .bg-brand-900{background-color:${palette[900]}!important}
    .text-brand-300{color:${palette[300]}!important}
    .text-brand-400{color:${palette[400]}!important}
    .text-brand-500{color:${palette[500]}!important}
    .text-brand-600{color:${palette[600]}!important}
    .text-brand-700{color:${palette[700]}!important}
    .border-brand-300{border-color:${palette[300]}!important}
    .border-brand-400{border-color:${palette[400]}!important}
    .border-brand-500{border-color:${palette[500]}!important}
    .ring-brand-500{--tw-ring-color:${palette[500]}!important}
    .from-brand-50{--tw-gradient-from:${palette[50]}!important}
    .from-brand-400{--tw-gradient-from:${palette[400]}!important}
    .from-brand-600{--tw-gradient-from:${palette[600]}!important}
    .to-brand-600{--tw-gradient-to:${palette[600]}!important}
    body { font-family: '${tweaks.fontDisplay}', 'Geist', system-ui, sans-serif; }
  `;
};

Object.assign(window, { TweaksPanel, TweaksContext, useTweaks, TWEAK_DEFAULTS, applyTweaks });
