import React, { useEffect, useMemo, useState } from 'react';
import ReactDOM from 'react-dom/client';
import Component from './Component';
import './dev-theme.css';
import { attachWindowSoundBridge, createDevHostBridge } from './devHostBridge';
import { metadata } from './index';

const mockConfig = {
  id: 'assumption-toggle-dev',
  name: metadata.name,
  version: metadata.version,
  params: metadata.defaultParams
};

const mockTheme = {
  primary: '#248a00',
  accent: '#1c6a00',
  bg: '#060807',
  bgSecondary: '#616161',
  text: '#f4f5ee',
  textMuted: '#b8c2b0',
  border: 'rgba(255,255,255,0.12)'
};

function DevHarness() {
  const [muted, setMuted] = useState(false);
  const [logEntries, setLogEntries] = useState<Array<{ id: string; detail: string }>>([]);

  const appendLog = (id: string, detail: string) => {
    setLogEntries((current) => [{ id, detail }, ...current].slice(0, 8));
  };

  const devHost = useMemo(() => createDevHostBridge({
    isMuted: () => muted,
    onSound: (id, payload) => {
      appendLog(id, payload ? JSON.stringify(payload) : 'play');
    },
    onEmit: (type, payload) => {
      appendLog(`event:${type}`, payload ? JSON.stringify(payload) : 'emit');
    }
  }), [muted]);

  useEffect(() => {
    return attachWindowSoundBridge(devHost);
  }, [devHost]);

  return (
    <div style={{ minHeight: '100vh', padding: '24px', position: 'relative' }}>
      <aside
        style={{
          position: 'fixed',
          top: 16,
          right: 16,
          width: 280,
          padding: 14,
          borderRadius: 14,
          background: 'rgba(6, 16, 11, 0.92)',
          border: '1px solid rgba(120,255,154,0.18)',
          color: '#dfffe7',
          fontFamily: 'Iceland, sans-serif',
          zIndex: 10,
          boxShadow: '0 12px 28px rgba(0,0,0,0.22)'
        }}
      >
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 10 }}>
          <strong style={{ fontFamily: 'Russo One, sans-serif', fontWeight: 400, letterSpacing: '0.06em' }}>
            Sound Bridge
          </strong>
          <button
            type="button"
            onClick={() => setMuted((current) => !current)}
            style={{
              border: '1px solid rgba(120,255,154,0.28)',
              background: muted ? 'rgba(96,20,20,0.92)' : 'rgba(14,40,20,0.92)',
              color: '#ecfff2',
              borderRadius: 999,
              padding: '6px 10px',
              cursor: 'pointer',
              fontFamily: 'Russo One, sans-serif',
              fontSize: 11,
              letterSpacing: '0.05em'
            }}
          >
            {muted ? 'Muted' : 'Live'}
          </button>
        </div>
        <div style={{ opacity: 0.78, marginBottom: 10, fontSize: 18 }}>
          Web Audio dev host listening for bridge calls
        </div>
        <div style={{ display: 'grid', gap: 6, fontSize: 18, lineHeight: 1.1 }}>
          {logEntries.length === 0 ? (
            <div style={{ opacity: 0.56 }}>No sound events yet.</div>
          ) : (
            logEntries.map((entry, index) => (
              <div
                key={`${entry.id}-${index}`}
                style={{
                  padding: '6px 8px',
                  borderRadius: 10,
                  background: 'rgba(255,255,255,0.04)',
                  border: '1px solid rgba(255,255,255,0.04)'
                }}
              >
                <div style={{ fontFamily: 'Russo One, sans-serif', fontSize: 11, letterSpacing: '0.05em' }}>{entry.id}</div>
                <div style={{ opacity: 0.78 }}>{entry.detail}</div>
              </div>
            ))
          )}
        </div>
      </aside>
      <Component
        config={mockConfig}
        theme={mockTheme}
        host={devHost}
        onComplete={(result) => {
          console.log('Assumption Toggle completed:', result);
        }}
        onProgress={(percent) => {
          console.log('Assumption Toggle progress:', percent);
        }}
      />
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('root')!).render(
  <React.StrictMode>
    <DevHarness />
  </React.StrictMode>
);
