import React, { useEffect, useMemo, useState } from 'react';
import { createRoot } from 'react-dom/client';
import {
  BarChart3,
  BookOpen,
  CalendarDays,
  CheckCircle2,
  ClipboardCheck,
  Cloud,
  CloudOff,
  Download,
  Fish,
  Flag,
  LayoutDashboard,
  Lightbulb,
  ListChecks,
  Plus,
  RotateCw,
  Save,
  Search,
  Send,
  Sigma,
  Target,
  Trash2,
  UserRoundCheck,
  Users,
  X
} from 'lucide-react';
import './styles.css';

const STORAGE_KEY = 'melhoria-continua-v2';
const API_ENTRY = './api/index.php';

const statusList = [
  { id: 'triagem', label: 'Triagem' },
  { id: 'analise', label: 'Análise' },
  { id: 'execucao', label: 'Execução' },
  { id: 'validacao', label: 'Validação' },
  { id: 'padronizado', label: 'Padronizado' }
];

const defaultPareto = [
  { cause: 'Falha de comunicação', count: 12 },
  { cause: 'Ausência de padrão', count: 9 },
  { cause: 'Treinamento insuficiente', count: 6 },
  { cause: 'Sistema/processo', count: 4 }
];

const defaultIshikawa = {
  method: ['Procedimento não padronizado'],
  people: ['Treinamento inconsistente'],
  machine: ['Ferramenta indisponível'],
  material: ['Informação incompleta'],
  measurement: ['Indicador não acompanhado'],
  environment: ['Mudança de prioridade no turno']
};

const defaultFiveW1H = [
  { what: 'Definir padrão de execução', why: 'Reduzir variação entre turnos', who: 'Supervisor', where: 'Operação', when: today(), how: 'Criar checklist e validar no gemba', howMuch: '', status: 'Pendente' }
];

const defaultSigma = {
  define: 'Descrever problema, cliente impactado e meta operacional.',
  measure: 'Coletar dados atuais e linha de base.',
  analyze: 'Identificar causa raiz com evidências.',
  improve: 'Testar solução piloto e medir ganho.',
  control: 'Padronizar, treinar e acompanhar aderência.'
};

const initialData = {
  activeModule: 'overview',
  activeImprovementId: null,
  improvements: [],
  actions: [],
  pdca: {},
  tools: {},
  meetings: [],
  requests: []
};

function today() {
  return new Date().toISOString().slice(0, 10);
}

function makeId(prefix) {
  return `${prefix}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 7)}`;
}

function wait(ms) {
  return new Promise((resolve) => {
    window.setTimeout(resolve, ms);
  });
}

function apiUrl(route) {
  return `${API_ENTRY}?route=${encodeURIComponent(route)}`;
}

function storageKey(companyId) {
  return `${STORAGE_KEY}-${companyId}`;
}

function loadCompanyLocal(companyId) {
  try {
    const saved = window.localStorage.getItem(storageKey(companyId));
    return saved ? normalizeData(JSON.parse(saved)) : initialData;
  } catch {
    return initialData;
  }
}

function normalizeData(data) {
  return {
    ...initialData,
    ...data,
    improvements: data?.improvements ?? [],
    actions: data?.actions ?? [],
    meetings: data?.meetings ?? [],
    requests: data?.requests ?? [],
    pdca: data?.pdca ?? {},
    tools: data?.tools ?? {}
  };
}

async function fetchJson(url, options) {
  const response = await fetch(url, { credentials: 'include', ...options });
  const text = await response.text();
  const contentType = response.headers.get('content-type') ?? '';
  if (!contentType.includes('application/json')) {
    throw new Error('A API não respondeu JSON. Verifique o backend.');
  }
  const payload = text ? JSON.parse(text) : {};
  if (!response.ok) {
    throw new Error(payload.error ?? 'Falha na API.');
  }
  return payload;
}

function statusLabel(status) {
  return statusList.find((item) => item.id === status)?.label ?? status;
}

function activeTools(data, id) {
  return data.tools[id] ?? {
    pareto: defaultPareto,
    ishikawa: defaultIshikawa,
    fivew1h: defaultFiveW1H,
    sigma: defaultSigma
  };
}

function App() {
  const [data, setData] = useState(initialData);
  const [query, setQuery] = useState('');
  const [sync, setSync] = useState({ online: false, status: 'offline', message: 'Modo offline local' });
  const [isImprovementModalOpen, setImprovementModalOpen] = useState(false);
  const [auth, setAuth] = useState(null);
  const [authLoading, setAuthLoading] = useState(true);

  const activeImprovement = data.improvements.find((item) => item.id === data.activeImprovementId)
    ?? data.improvements[0]
    ?? null;

  useEffect(() => {
    if (!auth?.company?.id) return;
    window.localStorage.setItem(storageKey(auth.company.id), JSON.stringify(data));
  }, [auth?.company?.id, data]);

  useEffect(() => {
    initializeSession();
  }, []);

  useEffect(() => {
    if (!auth || !sync.online) return;
    const timer = window.setTimeout(() => {
      saveToServer(data, false);
    }, 900);
    return () => window.clearTimeout(timer);
  }, [data, sync.online]);

  async function initializeSession() {
    try {
      const payload = await fetchJson(apiUrl('me'));
      if (payload.user) {
        setAuth(payload.user);
        setData(loadCompanyLocal(payload.user.company.id));
        await loadServerData();
      }
    } catch {
      setAuth(null);
    } finally {
      setAuthLoading(false);
    }
  }

  async function login(credentials) {
    const payload = await fetchJson(apiUrl('login'), {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(credentials)
    });
    setData(loadCompanyLocal(payload.user.company.id));
    setAuth(payload.user);
    await loadServerData();
  }

  async function logout() {
    await fetchJson(apiUrl('logout'), { method: 'POST' });
    setAuth(null);
    setData(initialData);
    setSync({ online: false, status: 'offline', message: 'Sessão encerrada' });
  }

  async function loadServerData() {
    try {
      const startupSteps = [
        'Conectando ao banco de dados...',
        'Checando migrations automáticas...',
        'Analisando tabelas e atualizações...',
        'Carregando dados do sistema...'
      ];

      for (const message of startupSteps.slice(0, 3)) {
        setSync({ online: false, status: 'syncing', message });
        await wait(520);
      }

      const health = await fetchJson(apiUrl('health'));
      const checkedTables = health.migration?.tables?.length ?? 0;
      setSync({
        online: false,
        status: 'syncing',
        message: checkedTables
          ? `Banco pronto: ${checkedTables} tabelas verificadas.`
          : startupSteps[3]
      });
      await wait(520);

      setSync({ online: false, status: 'syncing', message: startupSteps[3] });
      const payload = await fetchJson(apiUrl('continuous-data'));
      if (payload.user) setAuth(payload.user);
      const serverData = normalizeData({
        ...payload.data,
        activeModule: data.activeModule,
        activeImprovementId: payload.data?.improvements?.[0]?.id ?? null
      });
      setData(serverData);
      setSync({ online: true, status: 'online', message: 'MariaDB conectado e tabelas atualizadas' });
    } catch (error) {
      setSync({ online: false, status: 'offline', message: error.message || 'Modo offline local' });
    }
  }

  async function saveToServer(nextData, showMessage = true) {
    try {
      if (showMessage) setSync((current) => ({ ...current, status: 'syncing', message: 'Sincronizando...' }));
      await fetchJson(apiUrl('continuous-data'), {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ data: nextData })
      });
      setSync({
        online: true,
        status: showMessage ? 'online' : 'idle',
        message: showMessage ? 'Dados sincronizados' : ''
      });
    } catch (error) {
      setSync({ online: false, status: 'offline', message: error.message || 'Salvo apenas offline' });
    }
  }

  const filteredImprovements = useMemo(() => {
    const normalized = query.trim().toLowerCase();
    if (!normalized) return data.improvements;
    return data.improvements.filter((item) => [
      item.title,
      item.area,
      item.supervisor,
      item.problem,
      item.expectedGain,
      item.priority,
      statusLabel(item.status)
    ].join(' ').toLowerCase().includes(normalized));
  }, [data.improvements, query]);

  const updateData = (updater) => setData((current) => normalizeData(typeof updater === 'function' ? updater(current) : updater));
  const setActiveModule = (activeModule) => updateData((current) => ({ ...current, activeModule }));
  const selectImprovement = (id) => {
    updateData((current) => ({ ...current, activeImprovementId: id }));
    setImprovementModalOpen(true);
  };

  const ensureToolData = (id, current) => ({
    ...current.tools,
    [id]: activeTools(current, id)
  });

  const addImprovement = (source = {}) => {
    const id = makeId('mc');
    const improvement = {
      id,
      title: source.title ?? 'Nova oportunidade de melhoria',
      area: source.area ?? 'Operação',
      supervisor: source.supervisor ?? '',
      problem: source.problem ?? '',
      expectedGain: source.expectedGain ?? '',
      status: 'triagem',
      priority: source.urgency === 'Alta' ? 'Alta' : 'Média',
      impact: source.urgency === 'Alta' ? 5 : 3,
      effort: 3,
      dueDate: today(),
      createdAt: today()
    };
    updateData((current) => ({
      ...current,
      activeModule: 'pipeline',
      activeImprovementId: id,
      improvements: [improvement, ...current.improvements],
      pdca: { ...current.pdca, [id]: { plan: '', do: '', check: '', act: '' } },
      tools: { ...current.tools, [id]: { pareto: defaultPareto, ishikawa: defaultIshikawa, fivew1h: defaultFiveW1H, sigma: defaultSigma } },
      requests: source.id ? current.requests.map((request) => request.id === source.id ? { ...request, status: 'convertida' } : request) : current.requests
    }));
    setImprovementModalOpen(true);
  };

  const updateImprovement = (id, patch) => updateData((current) => ({
    ...current,
    improvements: current.improvements.map((item) => item.id === id ? { ...item, ...patch } : item),
    tools: ensureToolData(id, current)
  }));

  const deleteImprovement = (id) => updateData((current) => {
    const { [id]: removedPdca, ...pdca } = current.pdca;
    const { [id]: removedTools, ...tools } = current.tools;
    const improvements = current.improvements.filter((item) => item.id !== id);
    return {
      ...current,
      improvements,
      actions: current.actions.filter((action) => action.improvementId !== id),
      pdca,
      tools,
      activeImprovementId: improvements[0]?.id ?? null
    };
  });

  const addAction = () => {
    if (!activeImprovement) return;
    const action = {
      id: makeId('act'),
      improvementId: activeImprovement.id,
      what: 'Nova ação',
      why: '',
      who: '',
      when: today(),
      where: activeImprovement.area,
      how: '',
      howMuch: '',
      status: 'Pendente'
    };
    updateData((current) => ({ ...current, activeModule: 'fivew2h', actions: [action, ...current.actions] }));
  };

  const updateAction = (id, patch) => updateData((current) => ({
    ...current,
    actions: current.actions.map((action) => action.id === id ? { ...action, ...patch } : action)
  }));

  const deleteAction = (id) => updateData((current) => ({ ...current, actions: current.actions.filter((action) => action.id !== id) }));

  const updatePdca = (phase, value) => {
    if (!activeImprovement) return;
    updateData((current) => ({
      ...current,
      pdca: {
        ...current.pdca,
        [activeImprovement.id]: {
          ...(current.pdca[activeImprovement.id] ?? { plan: '', do: '', check: '', act: '' }),
          [phase]: value
        }
      }
    }));
  };

  const updateTool = (tool, value) => {
    if (!activeImprovement) return;
    updateData((current) => ({
      ...current,
      tools: {
        ...current.tools,
        [activeImprovement.id]: {
          ...activeTools(current, activeImprovement.id),
          [tool]: value
        }
      }
    }));
  };

  const addMeeting = () => updateData((current) => ({
    ...current,
    activeModule: 'meetings',
    meetings: [{
      id: makeId('meet'),
      date: today(),
      supervisor: activeImprovement?.supervisor ?? '',
      area: activeImprovement?.area ?? 'Operação',
      topic: activeImprovement?.title ?? 'Alinhamento operacional',
      decisions: '',
      nextStep: ''
    }, ...current.meetings]
  }));

  const updateMeeting = (id, patch) => updateData((current) => ({
    ...current,
    meetings: current.meetings.map((meeting) => meeting.id === id ? { ...meeting, ...patch } : meeting)
  }));

  const deleteMeeting = (id) => updateData((current) => ({ ...current, meetings: current.meetings.filter((meeting) => meeting.id !== id) }));

  const submitSupervisorRequest = async (request) => {
    const prepared = { ...request, id: makeId('req'), status: 'nova', createdAt: today() };
    updateData((current) => ({ ...current, requests: [prepared, ...current.requests] }));
    if (sync.online) {
      try {
        await fetchJson(apiUrl('supervisor-request'), {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(prepared)
        });
        setSync({ online: true, status: 'online', message: 'Solicitação enviada ao MariaDB' });
      } catch (error) {
        setSync({ online: false, status: 'offline', message: 'Solicitação salva offline para sincronizar depois' });
      }
    }
  };

  const exportData = () => {
    const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = `melhoria-continua-${today()}.json`;
    link.click();
    URL.revokeObjectURL(url);
  };

  const tools = activeImprovement ? activeTools(data, activeImprovement.id) : null;

  if (authLoading) {
    return <BootScreen text="Verificando sessão..." />;
  }

  if (!auth) {
    return <LoginScreen onLogin={login} />;
  }

  return (
    <div className="app-shell">
      <Sidebar activeModule={data.activeModule} onModuleChange={setActiveModule} sync={sync} auth={auth} onLogout={logout} />

      <main className="workspace">
        <header className="topbar">
          <div>
            {data.activeModule === 'pipeline' && (
              <>
                <span className="eyebrow">Analista de Melhoria Contínua</span>
                <h1>Sistema de melhoria contínua operacional</h1>
              </>
            )}
          </div>
          <div className="topbar-actions">
            <div className="search-box">
              <Search size={18} />
              <input value={query} onChange={(event) => setQuery(event.target.value)} placeholder="Buscar melhoria, área ou supervisor" />
            </div>
            <button className="secondary-button" type="button" onClick={loadServerData}>
              <RotateCw size={18} /> Sincronizar
            </button>
            <button className="secondary-button" type="button" onClick={exportData}>
              <Download size={18} /> Exportar
            </button>
            <button className="primary-button" type="button" onClick={() => addImprovement()}>
              <Plus size={18} /> Nova melhoria
            </button>
          </div>
        </header>

        {sync.status !== 'idle' && <SyncBanner sync={sync} />}

        <section className="module-content full">
          {data.activeModule === 'overview' && (
            <Overview improvements={filteredImprovements} actions={data.actions} requests={data.requests} onModuleChange={setActiveModule} onSelect={selectImprovement} />
          )}

          {data.activeModule === 'pipeline' && (
            <Pipeline improvements={filteredImprovements} activeId={activeImprovement?.id} onSelect={selectImprovement} onStatusChange={updateImprovement} />
          )}

          {['fivew1h', 'fivew2h'].includes(data.activeModule) && (
            <FiveWTwoH activeImprovement={activeImprovement} actions={data.actions} onAdd={addAction} onUpdate={updateAction} onDelete={deleteAction} />
          )}

          {data.activeModule === 'pdca' && (
            <Pdca improvement={activeImprovement} pdca={activeImprovement ? data.pdca[activeImprovement.id] : null} onUpdate={updatePdca} />
          )}

          {data.activeModule === 'pareto' && (
            tools ? <Pareto pareto={tools.pareto} onChange={(value) => updateTool('pareto', value)} /> : <Empty title="Selecione uma melhoria" text="Crie ou selecione uma melhoria para montar o Pareto." />
          )}

          {data.activeModule === 'ishikawa' && (
            tools ? <Ishikawa ishikawa={tools.ishikawa} onChange={(value) => updateTool('ishikawa', value)} /> : <Empty title="Selecione uma melhoria" text="Crie ou selecione uma melhoria para analisar causa raiz." />
          )}

          {data.activeModule === 'sigma' && (
            tools ? <SixSigma sigmaData={tools.sigma} onChange={(value) => updateTool('sigma', value)} /> : <Empty title="Selecione uma melhoria" text="Crie ou selecione uma melhoria para preencher o DMAIC." />
          )}

          {data.activeModule === 'meetings' && (
            <Meetings meetings={data.meetings} onAdd={addMeeting} onUpdate={updateMeeting} onDelete={deleteMeeting} />
          )}

          {data.activeModule === 'matrix' && (
            <Matrix improvements={filteredImprovements} onSelect={selectImprovement} />
          )}

          {data.activeModule === 'library' && <Library />}
        </section>

        {activeImprovement && isImprovementModalOpen && (
          <ImprovementDrawer
            improvement={activeImprovement}
            onClose={() => setImprovementModalOpen(false)}
            onUpdate={(patch) => updateImprovement(activeImprovement.id, patch)}
            onDelete={() => {
              deleteImprovement(activeImprovement.id);
              setImprovementModalOpen(false);
            }}
          />
        )}
      </main>
    </div>
  );
}

function BootScreen({ text }) {
  return (
    <main className="login-page">
      <section className="login-card compact">
        <span className="sync-loader" aria-hidden="true" />
        <strong>{text}</strong>
      </section>
    </main>
  );
}

function LoginScreen({ onLogin }) {
  const [form, setForm] = useState({ email: '', password: '' });
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(false);
  const update = (field, value) => setForm((current) => ({ ...current, [field]: value }));

  async function submit(event) {
    event.preventDefault();
    setLoading(true);
    setError('');
    try {
      await onLogin(form);
    } catch (exception) {
      setError(exception.message || 'Falha no login.');
    } finally {
      setLoading(false);
    }
  }

  return (
    <main className="login-page">
      <form className="login-card" onSubmit={submit}>
        <div className="brand-mark"><ClipboardCheck size={24} /></div>
        <div>
          <span className="eyebrow">Acesso restrito</span>
          <h1>Melhoria Contínua</h1>
          <p>Entre com o usuário da empresa para visualizar apenas os dados permitidos.</p>
        </div>
        {error && <div className="login-error">{error}</div>}
        <label>
          <span>E-mail</span>
          <input type="email" required value={form.email} onChange={(event) => update('email', event.target.value)} placeholder="email@empresa.com.br" />
        </label>
        <label>
          <span>Senha</span>
          <input type="password" required value={form.password} onChange={(event) => update('password', event.target.value)} placeholder="Senha" />
        </label>
        <button className="primary-button" type="submit" disabled={loading}>
          {loading ? 'Entrando...' : 'Entrar'}
        </button>
      </form>
    </main>
  );
}

function Sidebar({ activeModule, onModuleChange, sync, auth, onLogout }) {
  const modules = [
    { id: 'overview', label: 'Visão geral', icon: LayoutDashboard },
    { id: 'pipeline', label: 'Pipeline de melhorias', icon: Lightbulb },
    { id: 'fivew2h', label: '5W2H / ações', icon: ListChecks },
    { id: 'pdca', label: 'PDCA', icon: Target },
    { id: 'pareto', label: 'Pareto', icon: BarChart3 },
    { id: 'ishikawa', label: 'Ishikawa', icon: Fish },
    { id: 'sigma', label: 'Six Sigma DMAIC', icon: Sigma },
    { id: 'meetings', label: 'Reuniões', icon: CalendarDays },
    { id: 'matrix', label: 'Impacto x esforço', icon: Flag },
    { id: 'library', label: 'Biblioteca', icon: BookOpen }
  ];

  const companySlug = auth?.company?.slug ?? 'meli';

  return (
    <aside className="sidebar">
      <div className="brand">
        <div className="brand-mark"><ClipboardCheck size={24} /></div>
        <div>
          <strong>Melhoria Contínua</strong>
          <span>Operação e supervisão</span>
        </div>
      </div>
      <div className={sync.online ? 'sync-pill online' : 'sync-pill offline'}>
        {sync.online ? <Cloud size={16} /> : <CloudOff size={16} />}
        <span>{sync.online ? 'Banco online' : 'Modo offline'}</span>
      </div>
      <div className="tenant-pill">
        <strong>{auth?.company?.name}</strong>
        <span>{auth?.email}</span>
      </div>
      <nav className="nav-list" aria-label="Módulos">
        {modules.map((module) => {
          const Icon = module.icon;
          return (
            <button key={module.id} className={activeModule === module.id ? 'nav-item active' : 'nav-item'} type="button" onClick={() => onModuleChange(module.id)}>
              <Icon size={18} />
              <span>{module.label}</span>
            </button>
          );
        })}
      </nav>
      <a className="sidebar-link" href={`./supervisor.html?company=${companySlug}`} target="_blank" rel="noopener noreferrer">
        <UserRoundCheck size={16} />
        <span>Formulário supervisor</span>
      </a>
      <a className="sidebar-link compact" href={`./status.html?company=${companySlug}`} target="_blank" rel="noopener noreferrer">
        <ListChecks size={16} />
        <span>Consulta pública</span>
      </a>
      <button className="sidebar-logout" type="button" onClick={onLogout}>Sair</button>
    </aside>
  );
}

function SyncBanner({ sync }) {
  return (
    <section className={`sync-banner ${sync.status}`}>
      {sync.status === 'syncing' && <span className="sync-loader" aria-hidden="true" />}
      {sync.status !== 'syncing' && (sync.online ? <Cloud size={18} /> : <CloudOff size={18} />)}
      <span>{sync.message}</span>
    </section>
  );
}

function Overview({ improvements, actions, requests, onModuleChange, onSelect }) {
  const active = improvements.filter((item) => item.status !== 'padronizado').length;
  const done = improvements.filter((item) => item.status === 'padronizado').length;
  const lateActions = actions.filter((action) => action.status !== 'Concluída' && action.when < today()).length;
  const openRequests = requests.filter((request) => request.status === 'nova').length;

  return (
    <>
      <section className="metric-grid">
        <Metric icon={Lightbulb} label="Melhorias ativas" value={active} detail="Da triagem à validação" />
        <Metric icon={CheckCircle2} label="Padronizadas" value={done} detail="Soluções sustentadas" />
        <Metric icon={CalendarDays} label="Ações vencidas" value={lateActions} detail="Pendências que precisam destravar" danger={lateActions > 0} />
        <Metric icon={Users} label="Pedidos de supervisores" value={openRequests} detail="Entradas aguardando análise" />
      </section>
      <section className="two-columns">
        <Panel title="Oportunidades em andamento" label="Pipeline" action="Abrir pipeline" onAction={() => onModuleChange('pipeline')}>
          {improvements.slice(0, 6).map((item) => (
            <button className="compact-item" type="button" key={item.id} onClick={() => onSelect(item.id)}>
              <strong>{item.title}</strong>
              <span>{item.area} · {item.supervisor || 'Sem supervisor'} · {statusLabel(item.status)}</span>
            </button>
          ))}
        </Panel>
        <Panel title="Próximos focos do analista" label="Rotina" action="Abrir solicitações" onAction={() => onModuleChange('supervisor')}>
          {requests.slice(0, 6).map((request) => (
            <article className="compact-card" key={request.id}>
              <strong>{request.title}</strong>
              <span>{request.area} · {request.supervisor || 'Supervisor não informado'} · Urgência {request.urgency}</span>
            </article>
          ))}
        </Panel>
      </section>
    </>
  );
}

function Metric({ icon: Icon, label, value, detail, danger = false }) {
  return (
    <section className={danger ? 'metric-card danger' : 'metric-card'}>
      <div className="metric-icon"><Icon size={22} /></div>
      <div>
        <span>{label}</span>
        <strong>{value}</strong>
        <small>{detail}</small>
      </div>
    </section>
  );
}

function Panel({ title, label, action, onAction, children }) {
  return (
    <section className="panel">
      <header className="panel-header">
        <div>
          <span>{label}</span>
          <h2>{title}</h2>
        </div>
        {action && <button className="ghost-button" type="button" onClick={onAction}>{action}</button>}
      </header>
      <div className="compact-list">{children}</div>
    </section>
  );
}

function Modal({ title, label, onClose, children }) {
  return (
    <div className="modal-backdrop" role="presentation" onMouseDown={onClose}>
      <section className="modal-card" role="dialog" aria-modal="true" aria-label={title} onMouseDown={(event) => event.stopPropagation()}>
        <header className="modal-header">
          <div>
            <span>{label}</span>
            <h2>{title}</h2>
          </div>
          <button className="icon-button" type="button" onClick={onClose} aria-label="Fechar modal">
            <X size={18} />
          </button>
        </header>
        {children}
      </section>
    </div>
  );
}

function SupervisorForm({ onSubmit, requests, onConvert }) {
  const [isOpen, setOpen] = useState(false);
  const [form, setForm] = useState({ title: '', area: '', supervisor: '', problem: '', expectedGain: '', urgency: 'Média' });
  const update = (field, value) => setForm((current) => ({ ...current, [field]: value }));
  const submit = (event) => {
    event.preventDefault();
    onSubmit(form);
    setForm({ title: '', area: '', supervisor: '', problem: '', expectedGain: '', urgency: 'Média' });
    setOpen(false);
  };

  return (
    <section className="panel">
      <header className="panel-header">
        <div>
          <span>Fila do analista</span>
          <h2>Solicitações recebidas dos supervisores</h2>
        </div>
        <button className="primary-button" type="button" onClick={() => setOpen(true)}><Plus size={18} /> Nova solicitação</button>
      </header>
      <div className="compact-list">
        {requests.map((request) => (
          <article className="request-card" key={request.id}>
            <strong>{request.title}</strong>
            <span>{request.area} · {request.supervisor} · {request.urgency}</span>
            <p>{request.problem}</p>
            <button className="secondary-button" type="button" onClick={() => onConvert(request)}>Converter em melhoria</button>
          </article>
        ))}
        {!requests.length && <Empty title="Nenhuma solicitação recebida" text="Abra o formulário e registre a primeira oportunidade enviada pela supervisão." />}
      </div>

      {isOpen && (
        <Modal title="Formulário para supervisor" label="Entrada da operação" onClose={() => setOpen(false)}>
          <form className="modal-form supervisor-form" onSubmit={submit}>
            <label><span>Título da oportunidade</span><input required value={form.title} onChange={(event) => update('title', event.target.value)} /></label>
            <div className="field-grid">
              <label><span>Área</span><input required value={form.area} onChange={(event) => update('area', event.target.value)} /></label>
              <label><span>Supervisor</span><input required value={form.supervisor} onChange={(event) => update('supervisor', event.target.value)} /></label>
            </div>
            <label><span>Problema observado</span><textarea required value={form.problem} onChange={(event) => update('problem', event.target.value)} /></label>
            <label><span>Ganho esperado</span><textarea value={form.expectedGain} onChange={(event) => update('expectedGain', event.target.value)} /></label>
            <label><span>Urgência</span><select value={form.urgency} onChange={(event) => update('urgency', event.target.value)}><option>Alta</option><option>Média</option><option>Baixa</option></select></label>
            <div className="modal-actions">
              <button className="secondary-button" type="button" onClick={() => setOpen(false)}>Cancelar</button>
              <button className="primary-button" type="submit"><Send size={18} /> Enviar para análise</button>
            </div>
          </form>
        </Modal>
      )}
    </section>
  );
}

function Pipeline({ improvements, activeId, onSelect, onStatusChange }) {
  return (
    <section className="pipeline-section">
      <div className="kanban-header">
        <h2>Pipeline de melhorias</h2>
      </div>
      <div className="kanban-wrapper">
        <div className="kanban">
          {statusList.map((status) => {
            const items = improvements.filter((item) => item.status === status.id);
            return (
              <div className="kanban-column" key={status.id}>
                <header>
                  <h2>{status.label}</h2>
                  <span>{items.length}</span>
                </header>
                <div className="kanban-list">
                  {items.map((item) => (
                    <button key={item.id} type="button" className={activeId === item.id ? 'improvement-card active' : 'improvement-card'} onClick={() => onSelect(item.id)}>
                      <strong>{item.title}</strong>
                      <span>{item.area} · {item.supervisor || 'Sem supervisor'}</span>
                      <small>Prioridade {item.priority} · Impacto {item.impact}/5 · Esforço {item.effort}/5</small>
                      <div className="status-actions">
                        {statusList.map((next) => (
                          <span
                            key={next.id}
                            className={next.id === item.status ? 'status-dot selected' : 'status-dot'}
                            onClick={(event) => { event.stopPropagation(); onStatusChange(item.id, { status: next.id }); }}
                            title={next.label}
                          />
                        ))}
                      </div>
                    </button>
                  ))}
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </section>
  );
}

function FiveWTwoH({ activeImprovement, actions, onAdd, onUpdate, onDelete }) {
  const filtered = activeImprovement ? actions.filter((action) => action.improvementId === activeImprovement.id) : actions;
  return (
    <section className="panel">
      <header className="panel-header">
        <div><span>5W2H</span><h2>Plano de ação com custo e execução claros</h2></div>
        <button className="primary-button" type="button" onClick={onAdd}><Plus size={18} /> Nova ação</button>
      </header>
      <div className="action-table">
        {filtered.map((action) => (
          <article className="action-row" key={action.id}>
            <input value={action.what} onChange={(event) => onUpdate(action.id, { what: event.target.value })} placeholder="What / O quê" />
            <input value={action.why} onChange={(event) => onUpdate(action.id, { why: event.target.value })} placeholder="Why / Por quê" />
            <input value={action.who} onChange={(event) => onUpdate(action.id, { who: event.target.value })} placeholder="Who / Quem" />
            <input value={action.where} onChange={(event) => onUpdate(action.id, { where: event.target.value })} placeholder="Where / Onde" />
            <input type="date" value={action.when} onChange={(event) => onUpdate(action.id, { when: event.target.value })} />
            <input value={action.how} onChange={(event) => onUpdate(action.id, { how: event.target.value })} placeholder="How / Como" />
            <input value={action.howMuch ?? ''} onChange={(event) => onUpdate(action.id, { howMuch: event.target.value })} placeholder="How much / Quanto" />
            <select value={action.status} onChange={(event) => onUpdate(action.id, { status: event.target.value })}><option>Pendente</option><option>Em andamento</option><option>Concluída</option></select>
            <button className="icon-danger" type="button" onClick={() => onDelete(action.id)}><Trash2 size={17} /></button>
          </article>
        ))}
      </div>
    </section>
  );
}

function Pdca({ improvement, pdca, onUpdate }) {
  if (!improvement) return <Empty title="Selecione uma melhoria" text="Crie ou selecione uma oportunidade para montar o ciclo PDCA." />;
  const phases = [['plan', 'Plan', 'Planejar'], ['do', 'Do', 'Executar'], ['check', 'Check', 'Verificar'], ['act', 'Act', 'Padronizar']];
  return <section className="pdca-grid">{phases.map(([key, label, title]) => <article className="pdca-card" key={key}><span>{label}</span><h2>{title}</h2><textarea value={pdca?.[key] ?? ''} onChange={(event) => onUpdate(key, event.target.value)} /></article>)}</section>;
}

function Pareto({ pareto, onChange }) {
  const rows = [...pareto].sort((a, b) => Number(b.count) - Number(a.count));
  const total = rows.reduce((sum, item) => sum + Number(item.count || 0), 0) || 1;
  let cumulative = 0;
  const update = (index, patch) => onChange(pareto.map((item, itemIndex) => itemIndex === index ? { ...item, ...patch } : item));
  return (
    <section className="panel">
      <header className="panel-header"><div><span>Pareto</span><h2>Priorize as poucas causas vitais</h2></div><button className="primary-button" type="button" onClick={() => onChange([...pareto, { cause: 'Nova causa', count: 1 }])}><Plus size={18} /> Causa</button></header>
      <div className="pareto-list">
        {rows.map((item, sortedIndex) => {
          const originalIndex = pareto.findIndex((cause) => cause === item);
          cumulative += Number(item.count || 0);
          const percent = Math.round((Number(item.count || 0) / total) * 100);
          const cumulativePercent = Math.round((cumulative / total) * 100);
          return <article className="pareto-row" key={`${item.cause}-${sortedIndex}`}><input value={item.cause} onChange={(event) => update(originalIndex, { cause: event.target.value })} /><input type="number" min="0" value={item.count} onChange={(event) => update(originalIndex, { count: Number(event.target.value) })} /><div className="bar"><span style={{ width: `${percent}%` }} /></div><strong>{percent}%</strong><small>Acumulado {cumulativePercent}%</small></article>;
        })}
      </div>
    </section>
  );
}

function Ishikawa({ ishikawa, onChange }) {
  const categories = [['method', 'Método'], ['people', 'Mão de obra'], ['machine', 'Máquina'], ['material', 'Material'], ['measurement', 'Medição'], ['environment', 'Meio ambiente']];
  const updateCause = (key, index, value) => onChange({ ...ishikawa, [key]: (ishikawa[key] ?? []).map((item, itemIndex) => itemIndex === index ? value : item) });
  const addCause = (key) => onChange({ ...ishikawa, [key]: [...(ishikawa[key] ?? []), 'Nova causa'] });
  return <section className="ishikawa"><div className="fishbone-head">Problema</div>{categories.map(([key, label]) => <article className="fishbone-card" key={key}><header><h2>{label}</h2><button type="button" onClick={() => addCause(key)}>+</button></header>{(ishikawa[key] ?? []).map((cause, index) => <input key={`${key}-${index}`} value={cause} onChange={(event) => updateCause(key, index, event.target.value)} />)}</article>)}</section>;
}

function SixSigma({ sigmaData, onChange }) {
  const phases = [['define', 'Define', 'Definir problema, cliente e meta'], ['measure', 'Measure', 'Medir linha de base'], ['analyze', 'Analyze', 'Analisar causa raiz'], ['improve', 'Improve', 'Melhorar com piloto'], ['control', 'Control', 'Controlar e sustentar']];
  return <section className="sigma-grid">{phases.map(([key, label, helper]) => <article className="sigma-card" key={key}><span>{label}</span><h2>{helper}</h2><textarea value={sigmaData[key] ?? ''} onChange={(event) => onChange({ ...sigmaData, [key]: event.target.value })} /></article>)}</section>;
}

function Meetings({ meetings, onAdd, onUpdate, onDelete }) {
  return <section className="panel"><header className="panel-header"><div><span>Supervisores</span><h2>Ritual de acompanhamento</h2></div><button className="primary-button" type="button" onClick={onAdd}><Plus size={18} /> Nova reunião</button></header><div className="meeting-list">{meetings.map((meeting) => <article className="meeting-card" key={meeting.id}><div className="meeting-fields"><input type="date" value={meeting.date} onChange={(event) => onUpdate(meeting.id, { date: event.target.value })} /><input value={meeting.supervisor} onChange={(event) => onUpdate(meeting.id, { supervisor: event.target.value })} placeholder="Supervisor" /><input value={meeting.area} onChange={(event) => onUpdate(meeting.id, { area: event.target.value })} placeholder="Área" /><input value={meeting.topic} onChange={(event) => onUpdate(meeting.id, { topic: event.target.value })} placeholder="Pauta" /></div><textarea value={meeting.decisions} onChange={(event) => onUpdate(meeting.id, { decisions: event.target.value })} placeholder="Decisões tomadas" /><textarea value={meeting.nextStep} onChange={(event) => onUpdate(meeting.id, { nextStep: event.target.value })} placeholder="Próximo passo" /><button className="icon-danger" type="button" onClick={() => onDelete(meeting.id)}><Trash2 size={17} /></button></article>)}</div></section>;
}

function Matrix({ improvements, onSelect }) {
  return <section className="panel"><header className="panel-header"><div><span>Priorização</span><h2>Matriz impacto x esforço</h2></div></header><div className="matrix"><span className="axis y">Impacto</span><span className="axis x">Esforço</span>{improvements.map((item) => <button key={item.id} className="matrix-dot" type="button" style={{ left: `${item.effort * 18}%`, bottom: `${item.impact * 18}%` }} onClick={() => onSelect(item.id)} title={item.title}>{item.title.slice(0, 1)}</button>)}</div></section>;
}

function Library() {
  const tools = [['Pareto', 'Use para atacar as principais causas antes das causas menores.'], ['Ishikawa', 'Organize causas em método, pessoas, máquina, material, medição e ambiente.'], ['5W2H', 'Transforme solução em ação clara: o quê, por quê, quem, onde, quando, como e quanto custa.'], ['PDCA', 'Planeje, execute, verifique e padronize a melhoria.'], ['Six Sigma DMAIC', 'Estruture problemas complexos com dados e controle.'], ['Gemba', 'Valide o problema no local real da operação.']];
  return <section className="tool-grid">{tools.map(([title, description]) => <article className="tool-card" key={title}><BookOpen size={22} /><h2>{title}</h2><p>{description}</p></article>)}</section>;
}

function ImprovementDrawer({ improvement, onUpdate, onDelete, onClose }) {
  return (
    <Modal title={improvement.title} label="Melhoria selecionada" onClose={onClose}>
      <form className="modal-form" onSubmit={(event) => event.preventDefault()}>
        <label><span>Título</span><input value={improvement.title} onChange={(event) => onUpdate({ title: event.target.value })} /></label>
        <div className="field-grid">
          <label><span>Área</span><input value={improvement.area} onChange={(event) => onUpdate({ area: event.target.value })} /></label>
          <label><span>Supervisor</span><input value={improvement.supervisor} onChange={(event) => onUpdate({ supervisor: event.target.value })} /></label>
        </div>
        <label><span>Problema observado</span><textarea value={improvement.problem} onChange={(event) => onUpdate({ problem: event.target.value })} /></label>
        <label><span>Ganho esperado</span><textarea value={improvement.expectedGain} onChange={(event) => onUpdate({ expectedGain: event.target.value })} /></label>
        <div className="field-grid">
          <label><span>Status</span><select value={improvement.status} onChange={(event) => onUpdate({ status: event.target.value })}>{statusList.map((status) => <option key={status.id} value={status.id}>{status.label}</option>)}</select></label>
          <label><span>Prioridade</span><select value={improvement.priority} onChange={(event) => onUpdate({ priority: event.target.value })}><option>Alta</option><option>Média</option><option>Baixa</option></select></label>
        </div>
        <div className="field-grid">
          <label><span>Impacto: {improvement.impact}</span><input type="range" min="1" max="5" value={improvement.impact} onChange={(event) => onUpdate({ impact: Number(event.target.value) })} /></label>
          <label><span>Esforço: {improvement.effort}</span><input type="range" min="1" max="5" value={improvement.effort} onChange={(event) => onUpdate({ effort: Number(event.target.value) })} /></label>
        </div>
        <label><span>Prazo</span><input type="date" value={improvement.dueDate} onChange={(event) => onUpdate({ dueDate: event.target.value })} /></label>
        <div className="modal-actions">
          <button className="icon-danger" type="button" onClick={onDelete}><Trash2 size={18} /> Excluir</button>
          <button className="secondary-button" type="button" onClick={onClose}>Fechar</button>
        </div>
        <div className="save-hint"><Save size={16} /> Salvo localmente e sincronizado quando online</div>
      </form>
    </Modal>
  );
}

function Empty({ title, text }) {
  return <div className="empty-state"><Lightbulb size={30} /><strong>{title}</strong><span>{text}</span></div>;
}

createRoot(document.getElementById('root')).render(<App />);
