// tweaks-panel.jsx
// Drop-in replacement for the existing tweaks-panel.
// CHANGE: useTweaks(DEFAULTS) → useTweaks(DEFAULTS, 'tool-slug-name')
//
// Tool slugs to use (pass as the second argument):
//   Social Square        → 'social-square'
//   Partner Spotlight    → 'partner-spotlight'
//   Event Announcement   → 'event-announcement'
//   Carousel Cover       → 'carousel-cover'
//   Quote/Testimonial    → 'quote-testimonial'
//   Story Templates      → 'story-templates'
//   Highlight Covers     → 'highlight-covers'
//   Brand Post           → 'brand-post'
//   Feed Previewer       → 'feed-previewer'

// ─── useTweaks hook ─────────────────────────────────────────────────────────
//
// Usage in each tool:
//   const [tweaks, setTweak] = useTweaks(DEFAULTS, 'social-square');
//
// Returns:
//   tweaks   – current settings object (merge of defaults + saved values)
//   setTweak – (key, value) => void — update a single setting
//
// Data flow:
//   1. Mount: load from Supabase (if logged in) OR localStorage OR use DEFAULTS
//   2. Each setTweak: update React state, write to localStorage immediately,
//      schedule a debounced Supabase write (800ms)
//   3. Visual indicator: "Syncing…" / "Saved" / "Offline" chip

function useTweaks(defaults, toolName) {
  // ── state ──────────────────────────────────────────────────────────────
  const [tweaks, setTweaks] = React.useState(() => {
    // Synchronous initialisation from localStorage (Supabase load is async below)
    const lsKey = toolName ? `trylo_tweaks_${toolName}` : 'trylo_tweaks';
    try {
      const saved = localStorage.getItem(lsKey);
      if (saved) return { ...defaults, ...JSON.parse(saved) };
    } catch (e) {}
    return { ...defaults };
  });

  const [syncStatus, setSyncStatus] = React.useState('idle'); // idle | syncing | saved | offline
  const debounceRef = React.useRef(null);
  const userRef = React.useRef(null);

  // ── load from Supabase once auth is ready ──────────────────────────────
  React.useEffect(() => {
    if (!toolName || !window.__authReady) return;

    window.__authReady.then(async (user) => {
      userRef.current = user;
      if (!user || !window.__supabase) return;

      const cloudSettings = await window.__supabase.loadSettings(toolName, user.id);
      if (cloudSettings) {
        const merged = { ...defaults, ...cloudSettings };
        setTweaks(merged);
        // Keep localStorage in sync with what came from cloud
        try {
          localStorage.setItem(`trylo_tweaks_${toolName}`, JSON.stringify(merged));
        } catch (e) {}
      }
    });

    // Re-run when user signs in or out
    if (window.__authUI) {
      const unsub = window.__authUI.onAuthChange(async (auth) => {
        userRef.current = auth.user;
        if (!auth.user || !window.__supabase) return;
        const cloudSettings = await window.__supabase.loadSettings(toolName, auth.user.id);
        if (cloudSettings) {
          const merged = { ...defaults, ...cloudSettings };
          setTweaks(merged);
          try {
            localStorage.setItem(`trylo_tweaks_${toolName}`, JSON.stringify(merged));
          } catch (e) {}
        }
      });
      return unsub;
    }
  }, [toolName]);

  // ── setTweak: update one key, persist everywhere ───────────────────────
  function setTweak(key, value) {
    setTweaks((prev) => {
      const next = { ...prev, [key]: value };

      // 1. localStorage: immediate, synchronous
      const lsKey = toolName ? `trylo_tweaks_${toolName}` : 'trylo_tweaks';
      try { localStorage.setItem(lsKey, JSON.stringify(next)); } catch (e) {}

      // 2. Supabase: debounced 800ms
      if (toolName && window.__supabase && userRef.current) {
        setSyncStatus('syncing');
        clearTimeout(debounceRef.current);
        debounceRef.current = setTimeout(async () => {
          const ok = await window.__supabase.saveSettings(toolName, userRef.current.id, next);
          setSyncStatus(ok ? 'saved' : 'offline');
          // Reset indicator to idle after 2s
          setTimeout(() => setSyncStatus('idle'), 2000);
        }, 800);
      }

      return next;
    });
  }

  return [tweaks, setTweak, syncStatus];
}

// ─── SyncIndicator component ─────────────────────────────────────────────────
// Renders a small status chip.  Include once in each tool's root component:
//   <SyncIndicator status={syncStatus} />
function SyncIndicator({ status }) {
  if (status === 'idle') return null;

  const config = {
    syncing: { label: 'Syncing…', color: '#C26A41', dot: '⟳' },
    saved:   { label: 'Saved',    color: '#6B8C5E', dot: '✓' },
    offline: { label: 'Offline',  color: '#999',    dot: '⚠' },
  }[status] || null;

  if (!config) return null;

  return (
    <div style={{
      position: 'fixed',
      bottom: 16,
      right: 16,
      background: 'rgba(252,250,244,0.95)',
      border: `1px solid ${config.color}33`,
      borderRadius: 20,
      padding: '5px 12px',
      fontSize: 12,
      color: config.color,
      fontWeight: 500,
      boxShadow: '0 2px 8px rgba(26,22,18,0.08)',
      backdropFilter: 'blur(8px)',
      display: 'flex',
      alignItems: 'center',
      gap: 6,
      pointerEvents: 'none',
      zIndex: 9998,
      transition: 'opacity 0.2s',
    }}>
      <span>{config.dot}</span>
      <span>{config.label}</span>
    </div>
  );
}

// ─── Control components (unchanged from original) ───────────────────────────
// These are the building blocks used by each tool's tweaks panel.
// Preserve the exact component names and props your existing tools expect.

function TweaksPanel({ children, title }) {
  const [open, setOpen] = React.useState(true);

  return (
    <div style={{
      position: 'fixed',
      top: 16,
      left: 16,
      width: 260,
      background: 'rgba(252,250,244,0.97)',
      borderRadius: 12,
      border: '1px solid rgba(194,106,65,0.15)',
      boxShadow: '0 4px 20px rgba(26,22,18,0.10)',
      zIndex: 1000,
      backdropFilter: 'blur(8px)',
      overflow: 'hidden',
    }}>
      <div
        onClick={() => setOpen(!open)}
        style={{
          padding: '10px 14px',
          cursor: 'pointer',
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center',
          borderBottom: open ? '1px solid rgba(26,22,18,0.06)' : 'none',
        }}
      >
        <span style={{ fontSize: 13, fontWeight: 600, color: '#1A1612' }}>
          {title || 'Tweaks'}
        </span>
        <span style={{ fontSize: 11, color: '#999' }}>{open ? '▲' : '▼'}</span>
      </div>
      {open && (
        <div style={{ padding: '10px 14px', display: 'flex', flexDirection: 'column', gap: 10, maxHeight: '70vh', overflowY: 'auto' }}>
          {children}
        </div>
      )}
    </div>
  );
}

function TextControl({ label, value, onChange }) {
  return (
    <div>
      <label style={{ display: 'block', fontSize: 11, color: '#999', marginBottom: 4, textTransform: 'uppercase', letterSpacing: '0.04em' }}>
        {label}
      </label>
      <input
        type="text"
        value={value}
        onChange={(e) => onChange(e.target.value)}
        style={{
          width: '100%', padding: '6px 8px', border: '1.5px solid rgba(26,22,18,0.12)',
          borderRadius: 6, fontSize: 13, background: '#fff', color: '#1A1612',
          outline: 'none', boxSizing: 'border-box',
        }}
      />
    </div>
  );
}

function ColorControl({ label, value, onChange }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
      <label style={{ fontSize: 11, color: '#999', textTransform: 'uppercase', letterSpacing: '0.04em' }}>
        {label}
      </label>
      <input
        type="color"
        value={value}
        onChange={(e) => onChange(e.target.value)}
        style={{ width: 32, height: 24, border: 'none', borderRadius: 4, cursor: 'pointer', background: 'none' }}
      />
    </div>
  );
}

function SliderControl({ label, value, min = 0, max = 100, step = 1, onChange }) {
  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 4 }}>
        <label style={{ fontSize: 11, color: '#999', textTransform: 'uppercase', letterSpacing: '0.04em' }}>
          {label}
        </label>
        <span style={{ fontSize: 11, color: '#C26A41', fontWeight: 500 }}>{value}</span>
      </div>
      <input
        type="range"
        min={min} max={max} step={step}
        value={value}
        onChange={(e) => onChange(Number(e.target.value))}
        style={{ width: '100%', accentColor: '#C26A41' }}
      />
    </div>
  );
}

function SelectControl({ label, value, options, onChange }) {
  return (
    <div>
      <label style={{ display: 'block', fontSize: 11, color: '#999', marginBottom: 4, textTransform: 'uppercase', letterSpacing: '0.04em' }}>
        {label}
      </label>
      <select
        value={value}
        onChange={(e) => onChange(e.target.value)}
        style={{
          width: '100%', padding: '6px 8px', border: '1.5px solid rgba(26,22,18,0.12)',
          borderRadius: 6, fontSize: 13, background: '#fff', color: '#1A1612',
          outline: 'none', cursor: 'pointer',
        }}
      >
        {options.map((opt) => (
          <option key={opt.value ?? opt} value={opt.value ?? opt}>
            {opt.label ?? opt}
          </option>
        ))}
      </select>
    </div>
  );
}

function ToggleControl({ label, value, onChange }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
      <label style={{ fontSize: 11, color: '#999', textTransform: 'uppercase', letterSpacing: '0.04em' }}>
        {label}
      </label>
      <div
        onClick={() => onChange(!value)}
        style={{
          width: 36, height: 20, borderRadius: 10, cursor: 'pointer', transition: 'background 0.2s',
          background: value ? '#C26A41' : '#ddd', position: 'relative',
        }}
      >
        <div style={{
          position: 'absolute', top: 2, left: value ? 18 : 2, width: 16, height: 16,
          borderRadius: 8, background: '#fff', transition: 'left 0.2s',
        }} />
      </div>
    </div>
  );
}

// Divider for grouping controls visually
function TweaksDivider({ label }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 8, margin: '4px 0' }}>
      {label && <span style={{ fontSize: 10, color: '#bbb', textTransform: 'uppercase', letterSpacing: '0.06em', whiteSpace: 'nowrap' }}>{label}</span>}
      <div style={{ flex: 1, height: 1, background: 'rgba(26,22,18,0.08)' }} />
    </div>
  );
}
