
const SettingsModal = ({ isOpen, onClose }) => {
  const [activeTab, setActiveTab] = React.useState('tweaks'); // tweaks | integrations | advanced
  const [tweaks, setTweaks] = React.useState({
    accentColor: '#C9A84C',
    dataColor: '#4FC3F7',
    bgDarkness: 0.98,
    borderOpacity: 0.07,
    cardOpacity: 0.025,
    fontScale: 1,
    animationsEnabled: true,
  });
  const [integrations, setIntegrations] = React.useState(() => {
    const saved = localStorage.getItem('cipher-integrations');
    return saved ? JSON.parse(saved) : [];
  });
  const [newIntegration, setNewIntegration] = React.useState({ name: '', url: '', apiKey: '' });

  // Load tweaks on mount
  React.useEffect(() => {
    const saved = localStorage.getItem('cipher-tweaks');
    if (saved) {
      try {
        setTweaks(prev => ({ ...prev, ...JSON.parse(saved) }));
      } catch (e) {
        console.error('Failed to load tweaks:', e);
      }
    }
  }, []);

  const applyTweaks = (t) => {
    const root = document.documentElement;
    root.style.setProperty('--gold', t.accentColor);
    root.style.setProperty('--gold-dim', t.accentColor + '26');
    root.style.setProperty('--gold-glow', t.accentColor + '40');
    root.style.setProperty('--blue', t.dataColor);
    root.style.setProperty('--blue-dim', t.dataColor + '1F');
    root.style.setProperty('--blue-glow', t.dataColor + '40');
    
    const bgVal = Math.round(255 * (1 - t.bgDarkness));
    root.style.setProperty('--bg', `rgb(${bgVal},${bgVal},${bgVal})`);
    root.style.setProperty('--bg2', `rgb(${Math.round(bgVal * 1.1)},${Math.round(bgVal * 1.1)},${Math.round(bgVal * 1.1)})`);
    root.style.setProperty('--bg3', `rgb(${Math.round(bgVal * 1.2)},${Math.round(bgVal * 1.2)},${Math.round(bgVal * 1.2)})`);
    
    root.style.setProperty('--border', `rgba(255,255,255,${t.borderOpacity})`);
    root.style.setProperty('--card', `rgba(255,255,255,${t.cardOpacity})`);
    root.style.setProperty('--card-h', `rgba(255,255,255,${t.cardOpacity * 1.6})`);
    document.documentElement.style.setProperty('--font-scale', t.fontScale);
  };

  const updateTweak = (key, value) => {
    const newTweaks = { ...tweaks, [key]: value };
    setTweaks(newTweaks);
    localStorage.setItem('cipher-tweaks', JSON.stringify(newTweaks));
    applyTweaks(newTweaks);
  };

  const addIntegration = () => {
    if (!newIntegration.name.trim() || !newIntegration.url.trim()) {
      alert('Please fill in Name and URL');
      return;
    }
    const updated = [...integrations, { ...newIntegration, id: Date.now() }];
    setIntegrations(updated);
    localStorage.setItem('cipher-integrations', JSON.stringify(updated));
    setNewIntegration({ name: '', url: '', apiKey: '' });
  };

  const removeIntegration = (id) => {
    const updated = integrations.filter(i => i.id !== id);
    setIntegrations(updated);
    localStorage.setItem('cipher-integrations', JSON.stringify(updated));
  };

  const resetTweaks = () => {
    const defaults = {
      accentColor: '#C9A84C',
      dataColor: '#4FC3F7',
      bgDarkness: 0.98,
      borderOpacity: 0.07,
      cardOpacity: 0.025,
      fontScale: 1,
      animationsEnabled: true,
    };
    setTweaks(defaults);
    localStorage.setItem('cipher-tweaks', JSON.stringify(defaults));
    applyTweaks(defaults);
  };

  const accentOptions = [
    { name: 'Gold', color: '#C9A84C' },
    { name: 'Rose', color: '#E8886B' },
    { name: 'Cyan', color: '#4FC3F7' },
    { name: 'Purple', color: '#A78BFA' },
    { name: 'Teal', color: '#2DD4BF' },
    { name: 'Orange', color: '#F97316' },
  ];

  const s = {
    overlay: {
      position: 'fixed', inset: 0, zIndex: 9998,
      background: 'rgba(0,0,0,0.7)', backdropFilter: 'blur(8px)',
      display: isOpen ? 'flex' : 'none', alignItems: 'center', justifyContent: 'center',
      animation: isOpen ? 'fadeIn 0.2s ease-out' : 'none',
    },
    modal: {
      width: 720, maxHeight: '85vh', borderRadius: 12,
      background: 'rgba(10,10,10,0.97)', border: '1px solid rgba(201,168,76,0.15)',
      backdropFilter: 'blur(20px)', display: 'flex', flexDirection: 'column',
      boxShadow: '0 20px 60px rgba(0,0,0,0.6), 0 0 40px rgba(201,168,76,0.08)',
      overflow: 'hidden',
    },
    header: {
      padding: '24px 32px', borderBottom: '1px solid rgba(255,255,255,0.06)',
      display: 'flex', justifyContent: 'space-between', alignItems: 'center',
    },
    title: {
      fontFamily: "'Playfair Display',Georgia,serif", fontSize: 24, fontWeight: 700,
      color: '#E2E2E2',
    },
    closeBtn: {
      background: 'none', border: 'none', color: '#666', fontSize: 24,
      cursor: 'pointer', padding: 0, width: 32, height: 32,
      display: 'flex', alignItems: 'center', justifyContent: 'center',
    },
    tabs: {
      display: 'flex', padding: '0 32px', borderBottom: '1px solid rgba(255,255,255,0.04)',
      gap: 0,
    },
    tab: (isActive) => ({
      padding: '14px 18px', borderBottom: isActive ? '2px solid #C9A84C' : 'none',
      fontFamily: "'JetBrains Mono'", fontSize: 10, letterSpacing: '0.15em',
      color: isActive ? '#C9A84C' : '#666', cursor: 'pointer',
      background: 'none', border: 'none', transition: 'all 0.2s',
      textTransform: 'uppercase',
    }),
    content: {
      flex: 1, overflowY: 'auto', padding: '24px 32px',
    },
    section: {
      marginBottom: 28,
    },
    label: {
      fontFamily: "'JetBrains Mono'", fontSize: 10, letterSpacing: '0.2em',
      color: '#999', textTransform: 'uppercase', marginBottom: 12, display: 'block',
    },
    colorGrid: {
      display: 'grid', gridTemplateColumns: 'repeat(6, 1fr)', gap: 10,
    },
    colorSwatch: (color, isActive) => ({
      width: '100%', aspectRatio: '1', background: color,
      border: `2px solid ${isActive ? color : 'rgba(255,255,255,0.1)'}`,
      borderRadius: 8, cursor: 'pointer',
      boxShadow: isActive ? `0 0 12px ${color}80` : 'none',
      transition: 'all 0.2s',
    }),
    slider: {
      width: '100%', height: 6, borderRadius: 3, cursor: 'pointer',
      accentColor: '#C9A84C',
    },
    integrationCard: {
      padding: '14px 16px', background: 'rgba(255,255,255,0.03)',
      border: '1px solid rgba(255,255,255,0.06)', borderRadius: 6,
      marginBottom: 10, display: 'flex', justifyContent: 'space-between', alignItems: 'center',
    },
    input: {
      width: '100%', padding: '10px 12px', background: 'rgba(255,255,255,0.04)',
      border: '1px solid rgba(255,255,255,0.1)', borderRadius: 6,
      fontFamily: "'JetBrains Mono'", fontSize: 10, color: '#E2E2E2',
      marginBottom: 10, boxSizing: 'border-box',
    },
    button: (variant = 'primary') => ({
      padding: '10px 16px', borderRadius: 6, fontFamily: "'JetBrains Mono'", fontSize: 9,
      letterSpacing: '0.1em', cursor: 'pointer', transition: 'all 0.2s',
      border: variant === 'primary' ? '1px solid rgba(201,168,76,0.3)' : '1px solid rgba(255,255,255,0.1)',
      background: variant === 'primary' ? 'rgba(201,168,76,0.1)' : 'rgba(255,255,255,0.03)',
      color: variant === 'primary' ? '#C9A84C' : '#999',
    }),
  };

  if (!isOpen) return null;

  return (
    <div style={s.overlay} onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}>
      <div style={s.modal}>
        <div style={s.header}>
          <h2 style={s.title}>Settings & Configuration</h2>
          <button style={s.closeBtn} onClick={onClose}>✕</button>
        </div>

        <div style={s.tabs}>
          <button style={s.tab(activeTab === 'tweaks')} onClick={() => setActiveTab('tweaks')}>
            ⚙ Appearance
          </button>
          <button style={s.tab(activeTab === 'integrations')} onClick={() => setActiveTab('integrations')}>
            🔗 Integrations
          </button>
          <button style={s.tab(activeTab === 'advanced')} onClick={() => setActiveTab('advanced')}>
            ⚡ Advanced
          </button>
        </div>

        <div style={s.content}>
          {/* ── TWEAKS TAB ── */}
          {activeTab === 'tweaks' && (
            <>
              <div style={s.section}>
                <label style={s.label}>Accent Color</label>
                <div style={s.colorGrid}>
                  {accentOptions.map(opt => (
                    <button key={opt.color} style={s.colorSwatch(opt.color, tweaks.accentColor === opt.color)}
                      onClick={() => updateTweak('accentColor', opt.color)}
                      title={opt.name}/>
                  ))}
                </div>
              </div>

              <div style={s.section}>
                <label style={s.label}>Background Darkness ({Math.round(tweaks.bgDarkness * 100)}%)</label>
                <input type="range" min="0.85" max="1" step="0.01" value={tweaks.bgDarkness}
                  onChange={e => updateTweak('bgDarkness', parseFloat(e.target.value))}
                  style={s.slider}/>
              </div>

              <div style={s.section}>
                <label style={s.label}>Border Opacity ({Math.round(tweaks.borderOpacity * 100)}%)</label>
                <input type="range" min="0.02" max="0.15" step="0.01" value={tweaks.borderOpacity}
                  onChange={e => updateTweak('borderOpacity', parseFloat(e.target.value))}
                  style={s.slider}/>
              </div>

              <div style={s.section}>
                <label style={s.label}>Card Transparency ({Math.round(tweaks.cardOpacity * 100)}%)</label>
                <input type="range" min="0.01" max="0.08" step="0.005" value={tweaks.cardOpacity}
                  onChange={e => updateTweak('cardOpacity', parseFloat(e.target.value))}
                  style={s.slider}/>
              </div>

              <div style={s.section}>
                <label style={s.label}>Font Scale ({Math.round(tweaks.fontScale * 100)}%)</label>
                <input type="range" min="0.8" max="1.3" step="0.05" value={tweaks.fontScale}
                  onChange={e => updateTweak('fontScale', parseFloat(e.target.value))}
                  style={s.slider}/>
              </div>

              <button style={s.button('secondary')} onClick={resetTweaks}
                onMouseEnter={e => { e.currentTarget.style.background = 'rgba(255,255,255,0.08)'; }}
                onMouseLeave={e => { e.currentTarget.style.background = 'rgba(255,255,255,0.03)'; }}>
                Reset to Defaults
              </button>
            </>
          )}

          {/* ── INTEGRATIONS TAB ── */}
          {activeTab === 'integrations' && (
            <>
              <div style={s.section}>
                <label style={s.label}>Connected Tools</label>
                {integrations.length > 0 ? (
                  integrations.map(int => (
                    <div key={int.id} style={s.integrationCard}>
                      <div>
                        <div style={{ fontFamily: "'JetBrains Mono'", fontSize: 10, color: '#E2E2E2', marginBottom: 4 }}>
                          {int.name}
                        </div>
                        <div style={{ fontFamily: "'JetBrains Mono'", fontSize: 9, color: '#666' }}>
                          {int.url}
                        </div>
                      </div>
                      <button style={{ background: 'none', border: 'none', color: '#E05252', cursor: 'pointer', fontSize: 14 }}
                        onClick={() => removeIntegration(int.id)}>✕</button>
                    </div>
                  ))
                ) : (
                  <div style={{ fontSize: 11, color: '#666', padding: '12px 0' }}>
                    No integrations connected yet
                  </div>
                )}
              </div>

              <div style={s.section}>
                <label style={s.label}>Add New Integration</label>
                <input type="text" placeholder="Tool Name" value={newIntegration.name}
                  onChange={e => setNewIntegration({...newIntegration, name: e.target.value})}
                  style={s.input}/>
                <input type="text" placeholder="API Endpoint / URL" value={newIntegration.url}
                  onChange={e => setNewIntegration({...newIntegration, url: e.target.value})}
                  style={s.input}/>
                <input type="password" placeholder="API Key (optional)" value={newIntegration.apiKey}
                  onChange={e => setNewIntegration({...newIntegration, apiKey: e.target.value})}
                  style={s.input}/>
                <button style={s.button('primary')} onClick={addIntegration}
                  onMouseEnter={e => { e.currentTarget.style.boxShadow = '0 0 12px rgba(201,168,76,0.3)'; }}
                  onMouseLeave={e => { e.currentTarget.style.boxShadow = 'none'; }}>
                  + Add Integration
                </button>
              </div>

              <div style={{ padding: '12px 14px', background: 'rgba(79,195,247,0.08)', border: '1px solid rgba(79,195,247,0.2)',
                borderRadius: 6, fontSize: 11, color: '#4FC3F7', lineHeight: 1.7 }}>
                <strong>How to connect tools:</strong> Provide the API endpoint and key from your Claude Code tools. 
                Integrations will appear as tabs/panels in the dashboard for seamless access.
              </div>
            </>
          )}

          {/* ── ADVANCED TAB ── */}
          {activeTab === 'advanced' && (
            <>
              <div style={s.section}>
                <label style={s.label}>Data Management</label>
                <button style={{ ...s.button('secondary'), width: '100%', marginBottom: 10 }}
                  onClick={() => {
                    localStorage.clear();
                    alert('All data cleared. Refresh to reset.');
                  }}>
                  🗑 Clear All Data & Settings
                </button>
                <button style={{ ...s.button('secondary'), width: '100%', marginBottom: 10 }}
                  onClick={() => {
                    const data = {
                      tweaks: localStorage.getItem('cipher-tweaks'),
                      integrations: localStorage.getItem('cipher-integrations'),
                    };
                    const blob = new Blob([JSON.stringify(data, null, 2)], {type: 'application/json'});
                    const url = URL.createObjectURL(blob);
                    const a = document.createElement('a');
                    a.href = url;
                    a.download = 'cipher-backup.json';
                    a.click();
                  }}>
                  💾 Export Settings
                </button>
              </div>

              <div style={s.section}>
                <label style={s.label}>System Information</label>
                <div style={{ fontFamily: "'JetBrains Mono'", fontSize: 9, color: '#666', lineHeight: 1.8 }}>
                  <div>Version: CIPHER v4.1</div>
                  <div>Build: 2026.01</div>
                  <div>User: Afonso Marçal</div>
                  <div>Clearance: Level V</div>
                  <div>Status: All Systems Operational</div>
                </div>
              </div>

              <div style={{ padding: '12px 14px', background: 'rgba(224,82,82,0.08)', border: '1px solid rgba(224,82,82,0.2)',
                borderRadius: 6, fontSize: 11, color: '#E05252', lineHeight: 1.7 }}>
                <strong>Warning:</strong> Clearing data is irreversible. Make sure to export settings first if you need them.
              </div>
            </>
          )}
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { SettingsModal });
