// Shared views used across Geología, Fluidos y control de sólidos, Seguridad y medio ambiente.
// Each module routes sub=stock|reporte|programa|guardia to the corresponding template.

// ---------- Module wrapper ----------
function AreaModule({ area, sub }) {
  if (sub === 'stock') return <AreaStockView area={area} />;
  if (sub === 'reporte') return <AreaReportsView area={area} />;
  if (sub === 'programa') return <AreaProgramView area={area} />;
  if (sub === 'guardia') return <ShiftHandoverView area={area.label} />;
  return <AreaStockView area={area} />;
}

// Area config
const AREAS = {
  geologia: {
    id: 'geologia',
    label: 'Geología',
    icon: 'layers',
    accent: '#6366F1',
    stockSeed: [
      {
        id: 'g1',
        name: 'Bolsas de muestra (polietileno)',
        category: 'Consumible',
        qty: 420,
        min: 200,
        unit: 'u',
        lastMove: '2026-03-28',
      },
      {
        id: 'g2',
        name: 'Reactivo HCl 10%',
        category: 'Químico',
        qty: 8,
        min: 6,
        unit: 'L',
        lastMove: '2026-03-22',
      },
      {
        id: 'g3',
        name: 'Lupa binocular',
        category: 'Instrumento',
        qty: 2,
        min: 2,
        unit: 'u',
        lastMove: '2026-01-10',
      },
      {
        id: 'g4',
        name: 'Papel de archivo · registro',
        category: 'Consumible',
        qty: 32,
        min: 40,
        unit: 'u',
        lastMove: '2026-03-18',
      },
      {
        id: 'g5',
        name: 'Portaobjetos',
        category: 'Consumible',
        qty: 180,
        min: 100,
        unit: 'u',
        lastMove: '2026-03-26',
      },
    ],
    reportSeed: [
      {
        id: 'gr1',
        date: '2026-03-31',
        shift: 'Mañana',
        author: 'V. Méndez',
        depth: '1.897 m',
        formation: 'Fm. Vaca Muerta',
        tag: 'Litología',
      },
      {
        id: 'gr2',
        date: '2026-03-30',
        shift: 'Tarde',
        author: 'R. Ibáñez',
        depth: '1.866 m',
        formation: 'Fm. Vaca Muerta',
        tag: 'Paleontología',
      },
      {
        id: 'gr3',
        date: '2026-03-29',
        shift: 'Mañana',
        author: 'V. Méndez',
        depth: '1.835 m',
        formation: 'Fm. Quintuco',
        tag: 'Litología',
      },
      {
        id: 'gr4',
        date: '2026-03-28',
        shift: 'Noche',
        author: 'L. Peralta',
        depth: '1.812 m',
        formation: 'Fm. Quintuco',
        tag: 'Muestreo',
      },
    ],
    programHighlights: [
      'Muestreo cada 10 m desde 500 m hasta zona objetivo.',
      'Registro completo de litología y contenido paleontológico.',
      'Ensayo de reactividad (HCl 10%) en todas las muestras carbonáticas.',
      'Entrega de reporte final compilado al cierre del pozo.',
    ],
  },
  fluidos: {
    id: 'fluidos',
    label: 'Fluidos y control de sólidos',
    icon: 'droplet',
    accent: '#06B6D4',
    stockSeed: [
      {
        id: 'f1',
        name: 'Bentonita',
        category: 'Químico',
        qty: 1850,
        min: 600,
        unit: 'kg',
        lastMove: '2026-03-25',
      },
      {
        id: 'f2',
        name: 'Polímero PAC-R',
        category: 'Químico',
        qty: 180,
        min: 100,
        unit: 'kg',
        lastMove: '2026-03-22',
      },
      {
        id: 'f3',
        name: 'Lubricante de fluido',
        category: 'Químico',
        qty: 32,
        min: 40,
        unit: 'L',
        lastMove: '2026-03-18',
      },
      {
        id: 'f4',
        name: 'Inhibidor de corrosión',
        category: 'Químico',
        qty: 95,
        min: 40,
        unit: 'L',
        lastMove: '2026-03-10',
      },
      {
        id: 'f5',
        name: 'Mallas de zaranda (API 140)',
        category: 'Repuesto',
        qty: 6,
        min: 8,
        unit: 'u',
        lastMove: '2026-03-05',
      },
      {
        id: 'f6',
        name: 'Barita',
        category: 'Químico',
        qty: 2200,
        min: 800,
        unit: 'kg',
        lastMove: '2026-03-14',
      },
    ],
    reportSeed: [
      {
        id: 'fr1',
        date: '2026-03-31',
        shift: 'Tarde',
        author: 'S. Aguirre',
        depth: '1.897 m',
        formation: 'Densidad 1.18 g/cc · VP 22',
        tag: 'Análisis FQ',
      },
      {
        id: 'fr2',
        date: '2026-03-31',
        shift: 'Mañana',
        author: 'J. Pereyra',
        depth: '1.884 m',
        formation: 'pH 9.2 · Cl⁻ 12.000 ppm',
        tag: 'Control',
      },
      {
        id: 'fr3',
        date: '2026-03-30',
        shift: 'Tarde',
        author: 'S. Aguirre',
        depth: '1.866 m',
        formation: 'Filtrado 6.2 ml/30 min',
        tag: 'Análisis FQ',
      },
      {
        id: 'fr4',
        date: '2026-03-30',
        shift: 'Mañana',
        author: 'J. Pereyra',
        depth: '1.850 m',
        formation: 'Zaranda · 4% sólidos',
        tag: 'Sólidos',
      },
    ],
    programHighlights: [
      'Mantener densidad 1.15–1.22 g/cc en sección intermedia.',
      'Muestreo fisico-químico cada 3 horas + al cambio de turno.',
      'Zarandas API 140 en serie · control de recortes por turno.',
      'Limpieza de tanques tras cada sección de revestimiento.',
    ],
  },
  hse: {
    id: 'hse',
    label: 'Seguridad y medio ambiente',
    icon: 'shield',
    accent: '#DC2626',
    stockSeed: [
      {
        id: 'h1',
        name: 'Extintores 10 lbs PQS',
        category: 'Equipamiento',
        qty: 8,
        min: 6,
        unit: 'u',
        lastMove: '2026-03-04',
      },
      {
        id: 'h2',
        name: 'Guantes nitrilo talle L',
        category: 'EPP',
        qty: 80,
        min: 50,
        unit: 'par',
        lastMove: '2026-03-28',
      },
      {
        id: 'h3',
        name: 'Barbijos N95',
        category: 'EPP',
        qty: 32,
        min: 40,
        unit: 'u',
        lastMove: '2026-03-19',
      },
      {
        id: 'h4',
        name: 'Paños absorbentes oil-spill',
        category: 'Ambiente',
        qty: 40,
        min: 30,
        unit: 'u',
        lastMove: '2026-03-15',
      },
      {
        id: 'h5',
        name: 'Bolsas de residuos peligrosos',
        category: 'Ambiente',
        qty: 120,
        min: 60,
        unit: 'u',
        lastMove: '2026-03-22',
      },
    ],
    reportSeed: [
      {
        id: 'hr1',
        date: '2026-03-31',
        shift: '—',
        author: 'A. Ortiz',
        depth: '—',
        formation: 'Observación conductual',
        tag: 'Seguridad',
      },
      {
        id: 'hr2',
        date: '2026-03-30',
        shift: 'Tarde',
        author: 'A. Ortiz',
        depth: '—',
        formation: 'Derrame menor · hidrocarburo',
        tag: 'Ambiente',
      },
      {
        id: 'hr3',
        date: '2026-03-28',
        shift: '—',
        author: 'N. Suárez',
        depth: '—',
        formation: 'Simulacro de evacuación',
        tag: 'Simulacro',
      },
    ],
    programHighlights: [
      'Charlas de 5 minutos al inicio de cada turno.',
      'Inspección de EPP semanal · auditoría mensual.',
      'Plan de respuesta a derrames ≤ 30 minutos.',
      'Gestión de residuos peligrosos según norma SRT 319/99.',
    ],
  },
};

// ---------- Stock view (area-scoped) ----------
function AreaStockView({ area }) {
  const toast = useToast();
  const [items, setItems] = useState(area.stockSeed);
  const [q, setQ] = useState('');
  const [filter, setFilter] = useState('all');

  const lowCount = items.filter((i) => i.qty < i.min).length;
  const cats = Array.from(new Set(items.map((i) => i.category)));
  const filtered = items.filter((i) => {
    if (filter === 'low' && i.qty >= i.min) return false;
    if (filter !== 'all' && filter !== 'low' && i.category !== filter) return false;
    if (q && !i.name.toLowerCase().includes(q.toLowerCase())) return false;
    return true;
  });

  function adjust(id, delta) {
    setItems((arr) =>
      arr.map((i) =>
        i.id === id
          ? {
              ...i,
              qty: Math.max(0, i.qty + delta),
              lastMove: new Date().toISOString().slice(0, 10),
            }
          : i,
      ),
    );
    toast({
      title: delta > 0 ? 'Ingreso' : 'Egreso',
      description: 'Stock actualizado',
      variant: delta > 0 ? 'success' : 'default',
    });
  }

  return (
    <div className="view-in space-y-5">
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
        <KpiMini label="Ítems" value={items.length} sub={`${cats.length} categorías`} />
        <KpiMini
          label="Unidades"
          value={items.reduce((s, i) => s + i.qty, 0).toLocaleString('es-AR')}
          sub="suma total"
        />
        <KpiMini
          label="Stock bajo"
          value={lowCount}
          emph={lowCount > 0 ? 'red' : null}
          sub="ítems < mínimo"
        />
        <KpiMini label="Últ. movimiento" value="Hoy" sub="carga manual" />
      </div>

      <Card>
        <div className="px-5 py-3 border-b border-border flex flex-wrap items-center gap-3">
          <div className="relative">
            <Icon
              name="search"
              size={14}
              className="absolute left-2.5 top-1/2 -translate-y-1/2 text-slate-400"
            />
            <input
              value={q}
              onChange={(e) => setQ(e.target.value)}
              placeholder="Buscar ítem…"
              className="h-9 pl-8 pr-3 w-56 rounded-md border border-border text-[12.5px] focus:outline-none focus:ring-2 focus:ring-amber/30 focus:border-amber"
            />
          </div>
          <Tabs
            value={filter}
            onChange={setFilter}
            options={[
              { value: 'all', label: 'Todos' },
              { value: 'low', label: `Bajo · ${lowCount}` },
              ...cats.map((c) => ({ value: c, label: c })),
            ]}
          />
          <div className="ml-auto flex items-center gap-2">
            <Button variant="outline" size="sm">
              <Icon name="download" size={12} /> Exportar
            </Button>
            <Button variant="primary" size="sm">
              <Icon name="plus" size={12} /> Nuevo ítem
            </Button>
          </div>
        </div>
        <div className="overflow-x-auto">
          <table className="w-full text-[13px]">
            <thead>
              <tr className="bg-slate-50 text-[10.5px] font-semibold text-muted uppercase tracking-wider">
                <th className="text-left px-5 py-2.5">Ítem</th>
                <th className="text-left px-3 py-2.5">Categoría</th>
                <th className="text-right px-3 py-2.5">Cantidad</th>
                <th className="text-right px-3 py-2.5">Mínimo</th>
                <th className="px-3 py-2.5 w-48">Cobertura</th>
                <th className="text-right px-3 py-2.5">Últ. mov.</th>
                <th className="text-right px-5 py-2.5">Acciones</th>
              </tr>
            </thead>
            <tbody>
              {filtered.map((it) => {
                const pct = Math.min(100, (it.qty / Math.max(1, it.min)) * 50);
                const status = it.qty < it.min ? 'low' : it.qty < it.min * 1.5 ? 'warn' : 'ok';
                return (
                  <tr key={it.id} className="border-t border-border hover:bg-slate-50/60">
                    <td className="px-5 py-3 font-medium text-ink">{it.name}</td>
                    <td className="px-3 py-3">
                      <Badge variant="outline">{it.category}</Badge>
                    </td>
                    <td className="px-3 py-3 text-right tnum font-semibold">
                      {it.qty.toLocaleString('es-AR')}{' '}
                      <span className="text-[11px] text-muted font-normal">{it.unit}</span>
                    </td>
                    <td className="px-3 py-3 text-right tnum text-muted">
                      {it.min.toLocaleString('es-AR')} {it.unit}
                    </td>
                    <td className="px-3 py-3">
                      <div className="flex items-center gap-2">
                        <div className="flex-1 h-1.5 rounded-full bg-slate-100 overflow-hidden">
                          <div
                            className={cn(
                              'h-full rounded-full',
                              status === 'low'
                                ? 'bg-red'
                                : status === 'warn'
                                  ? 'bg-amber'
                                  : 'bg-emerald',
                            )}
                            style={{ width: `${Math.min(100, pct * 2)}%` }}
                          />
                        </div>
                        <span
                          className={cn(
                            'text-[10.5px] font-semibold tnum min-w-14 text-right',
                            status === 'low'
                              ? 'text-red'
                              : status === 'warn'
                                ? 'text-amber-ink'
                                : 'text-emerald',
                          )}
                        >
                          {status === 'low' ? 'Bajo' : status === 'warn' ? 'Alerta' : 'OK'}
                        </span>
                      </div>
                    </td>
                    <td className="px-3 py-3 text-right tnum text-muted text-[11.5px]">
                      {it.lastMove}
                    </td>
                    <td className="px-5 py-3 text-right">
                      <div className="inline-flex items-center gap-1">
                        <button
                          onClick={() => adjust(it.id, -1)}
                          className="h-7 w-7 rounded-md border border-border bg-white hover:bg-slate-50 flex items-center justify-center text-muted hover:text-ink"
                        >
                          <Icon name="minus" size={12} />
                        </button>
                        <button
                          onClick={() => adjust(it.id, 1)}
                          className="h-7 w-7 rounded-md border border-border bg-white hover:bg-slate-50 flex items-center justify-center text-muted hover:text-ink"
                        >
                          <Icon name="plus" size={12} />
                        </button>
                      </div>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      </Card>
    </div>
  );
}

function KpiMini({ label, value, sub, emph }) {
  return (
    <Card>
      <CardContent className="pt-5">
        <div className="text-[11px] font-semibold text-muted uppercase tracking-wider">{label}</div>
        <div
          className={cn(
            'text-[26px] font-bold tracking-tight tnum mt-2',
            emph === 'red' && 'text-red',
          )}
        >
          {value}
        </div>
        <div className="text-[11px] text-muted mt-1">{sub}</div>
      </CardContent>
    </Card>
  );
}

// ---------- Reports view (list + read + editable templates) ----------
function AreaReportsView({ area }) {
  const [mode, setMode] = useState('list'); // list | new | read | templates
  const [current, setCurrent] = useState(null);

  if (mode === 'read' && current) {
    return (
      <ReportReader
        area={area}
        report={current}
        onBack={() => {
          setMode('list');
          setCurrent(null);
        }}
      />
    );
  }
  if (mode === 'new') {
    return (
      <ReportBuilder area={area} onBack={() => setMode('list')} onSubmit={() => setMode('list')} />
    );
  }
  if (mode === 'templates') {
    return <TemplateEditor area={area} onBack={() => setMode('list')} />;
  }

  return (
    <div className="view-in space-y-5">
      <div className="flex items-center justify-between flex-wrap gap-3">
        <div>
          <h2 className="text-[18px] font-bold tracking-tight">Reportes · {area.label}</h2>
          <p className="text-[12px] text-muted mt-0.5">
            {area.reportSeed.length} reportes cargados · formulario editable por el cliente.
          </p>
        </div>
        <div className="flex items-center gap-2">
          <Button variant="outline" size="sm" onClick={() => setMode('templates')}>
            <Icon name="edit" size={12} /> Editar plantilla
          </Button>
          <Button variant="outline" size="sm">
            <Icon name="download" size={12} /> Exportar
          </Button>
          <Button variant="primary" size="sm" onClick={() => setMode('new')}>
            <Icon name="plus" size={12} /> Nuevo reporte
          </Button>
        </div>
      </div>

      <Card>
        <div className="overflow-x-auto">
          <table className="w-full text-[13px]">
            <thead>
              <tr className="bg-slate-50 text-[10.5px] font-semibold text-muted uppercase tracking-wider">
                <th className="text-left px-5 py-2.5">Fecha</th>
                <th className="text-left px-3 py-2.5">Turno</th>
                <th className="text-left px-3 py-2.5">Autor</th>
                <th className="text-left px-3 py-2.5">Tipo</th>
                <th className="text-left px-3 py-2.5">Profundidad</th>
                <th className="text-left px-3 py-2.5">Observación principal</th>
                <th className="text-right px-5 py-2.5">Acción</th>
              </tr>
            </thead>
            <tbody>
              {area.reportSeed.map((r) => (
                <tr key={r.id} className="border-t border-border hover:bg-slate-50/60">
                  <td className="px-5 py-3 tnum text-muted">{r.date}</td>
                  <td className="px-3 py-3">
                    <Badge variant="outline">{r.shift}</Badge>
                  </td>
                  <td className="px-3 py-3 font-medium">{r.author}</td>
                  <td className="px-3 py-3">
                    <Badge variant="amber">{r.tag}</Badge>
                  </td>
                  <td className="px-3 py-3 tnum">{r.depth}</td>
                  <td className="px-3 py-3 text-muted max-w-sm truncate">{r.formation}</td>
                  <td className="px-5 py-3 text-right">
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => {
                        setCurrent(r);
                        setMode('read');
                      }}
                    >
                      <Icon name="eye" size={12} /> Leer
                    </Button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </Card>
    </div>
  );
}

function ReportReader({ area, report, onBack }) {
  return (
    <div className="view-in space-y-5">
      <button
        onClick={onBack}
        className="text-[12px] text-muted hover:text-ink flex items-center gap-1"
      >
        <Icon name="chevronRight" size={11} className="rotate-180" /> Volver al listado
      </button>
      <Card>
        <CardHeader>
          <div className="flex items-start justify-between">
            <div>
              <Badge variant="amber">{report.tag}</Badge>
              <CardTitle className="mt-2">
                {area.label} · {report.formation}
              </CardTitle>
              <CardDescription>
                {report.date} · Turno {report.shift} · Autor {report.author}
              </CardDescription>
            </div>
            <div className="flex items-center gap-2">
              <Button variant="outline" size="sm">
                <Icon name="download" size={12} /> PDF
              </Button>
              <Button variant="outline" size="sm">
                <Icon name="edit" size={12} /> Editar
              </Button>
            </div>
          </div>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-2 lg:grid-cols-4 gap-4 text-[12.5px] border-t border-border pt-4">
            <InfoField label="Profundidad" value={report.depth} />
            <InfoField label="Formación" value={report.formation.split('·')[0]} />
            <InfoField label="Autor" value={report.author} />
            <InfoField label="Turno" value={report.shift} />
          </div>
          <div className="mt-6 prose max-w-none text-[13.5px] leading-relaxed text-ink">
            <h4 className="text-[13px] font-semibold uppercase tracking-wider text-muted mb-2">
              Resumen
            </h4>
            <p>
              Reporte de {area.label.toLowerCase()} del turno {report.shift} del {report.date}.
              Avance sobre el objetivo del pozo sin desviaciones mayores. Las mediciones se
              registran según la plantilla vigente del cliente.
            </p>
            <h4 className="text-[13px] font-semibold uppercase tracking-wider text-muted mt-5 mb-2">
              Observaciones
            </h4>
            <ul className="list-disc pl-5 space-y-1">
              <li>Muestra tomada a {report.depth} · sin anomalías visibles.</li>
              <li>Parámetros dentro del rango establecido por el programa.</li>
              <li>Próximo control a profundidad +10 m.</li>
            </ul>
            <h4 className="text-[13px] font-semibold uppercase tracking-wider text-muted mt-5 mb-2">
              Adjuntos
            </h4>
            <div className="flex flex-wrap gap-2">
              {['muestra-01.jpg', 'planilla-fq.xlsx', 'notas-campo.pdf'].map((f) => (
                <div
                  key={f}
                  className="flex items-center gap-2 px-3 py-1.5 rounded-md border border-border bg-slate-50 text-[12px]"
                >
                  <Icon name="file" size={12} className="text-muted" />
                  {f}
                </div>
              ))}
            </div>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}

function InfoField({ label, value }) {
  return (
    <div>
      <div className="text-[10px] font-semibold text-muted uppercase tracking-wider">{label}</div>
      <div className="text-[13.5px] font-medium mt-1 tnum">{value}</div>
    </div>
  );
}

function ReportBuilder({ area, onBack, onSubmit }) {
  const toast = useToast();
  // A sample dynamic form — the editable template concept:
  const template = getTemplate(area.id);
  const [values, setValues] = useState({});
  function set(k, v) {
    setValues((x) => ({ ...x, [k]: v }));
  }

  return (
    <div className="view-in space-y-5">
      <div className="flex items-center justify-between">
        <div>
          <button
            onClick={onBack}
            className="text-[12px] text-muted hover:text-ink flex items-center gap-1"
          >
            <Icon name="chevronRight" size={11} className="rotate-180" /> Volver
          </button>
          <h2 className="text-[18px] font-bold tracking-tight mt-2">
            Nuevo reporte · {area.label}
          </h2>
          <p className="text-[12px] text-muted mt-0.5">
            Plantilla: <b className="text-ink">{template.name}</b> ·{' '}
            <button className="text-amber hover:underline">Cambiar plantilla</button>
          </p>
        </div>
        <Badge variant="amber">Plantilla editable por cliente</Badge>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-5">
        <div className="lg:col-span-2 space-y-4">
          {template.sections.map((sec, si) => (
            <Card key={si}>
              <CardHeader>
                <CardTitle>{sec.title}</CardTitle>
                {sec.description && <CardDescription>{sec.description}</CardDescription>}
              </CardHeader>
              <CardContent className="grid grid-cols-2 gap-4 pt-0">
                {sec.fields.map((f, fi) => (
                  <div key={fi} className={f.full ? 'col-span-2' : ''}>
                    <Label>
                      {f.label}
                      {f.required && ' *'}
                    </Label>
                    {f.type === 'text' && (
                      <Input
                        value={values[f.key] || ''}
                        onChange={(e) => set(f.key, e.target.value)}
                        placeholder={f.ph}
                      />
                    )}
                    {f.type === 'number' && (
                      <Input
                        type="number"
                        value={values[f.key] ?? ''}
                        onChange={(e) => set(f.key, Number(e.target.value))}
                        placeholder={f.ph}
                      />
                    )}
                    {f.type === 'select' && (
                      <Select
                        value={values[f.key] || f.options[0]}
                        onChange={(e) => set(f.key, e.target.value)}
                      >
                        {f.options.map((o) => (
                          <option key={o}>{o}</option>
                        ))}
                      </Select>
                    )}
                    {f.type === 'textarea' && (
                      <Textarea
                        rows={3}
                        value={values[f.key] || ''}
                        onChange={(e) => set(f.key, e.target.value)}
                        placeholder={f.ph}
                      />
                    )}
                  </div>
                ))}
              </CardContent>
            </Card>
          ))}
        </div>
        <div>
          <Card className="sticky top-32">
            <CardHeader>
              <CardTitle>Envío</CardTitle>
              <CardDescription>
                El reporte se suma al listado y se incluye en el resumen ejecutivo.
              </CardDescription>
            </CardHeader>
            <CardContent className="pt-0 flex flex-col gap-3">
              <Button
                variant="primary"
                size="md"
                onClick={() => {
                  toast({ title: 'Reporte enviado', variant: 'success' });
                  onSubmit();
                }}
              >
                <Icon name="check" size={14} /> Enviar reporte
              </Button>
              <Button variant="outline" size="sm">
                Guardar borrador
              </Button>
              <div className="text-[11px] text-muted bg-slate-50 rounded-md p-2.5 border border-border flex gap-2">
                <Icon name="info" size={12} className="shrink-0 mt-0.5 text-muted" />
                <span>
                  La plantilla se puede personalizar desde <b>Editar plantilla</b>. Los cambios
                  afectan a futuros reportes.
                </span>
              </div>
            </CardContent>
          </Card>
        </div>
      </div>
    </div>
  );
}

function TemplateEditor({ area, onBack }) {
  const template = getTemplate(area.id);
  return (
    <div className="view-in space-y-5">
      <div className="flex items-center justify-between">
        <div>
          <button
            onClick={onBack}
            className="text-[12px] text-muted hover:text-ink flex items-center gap-1"
          >
            <Icon name="chevronRight" size={11} className="rotate-180" /> Volver
          </button>
          <h2 className="text-[18px] font-bold tracking-tight mt-2">Plantilla · {area.label}</h2>
          <p className="text-[12px] text-muted mt-0.5">
            El cliente puede agregar, quitar o reordenar campos. También guardar varias plantillas.
          </p>
        </div>
        <div className="flex items-center gap-2">
          <Button variant="outline" size="sm">
            <Icon name="plus" size={12} /> Nueva plantilla
          </Button>
          <Button variant="primary" size="sm">
            <Icon name="check" size={12} /> Guardar cambios
          </Button>
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-5">
        <Card className="lg:col-span-2">
          <CardHeader>
            <CardTitle>{template.name}</CardTitle>
            <CardDescription>
              Arrastrá los campos para reordenar · click en ✎ para editar.
            </CardDescription>
          </CardHeader>
          <CardContent className="pt-0 space-y-4">
            {template.sections.map((sec, si) => (
              <div key={si} className="rounded-md border border-border bg-slate-50/60">
                <div className="px-3 py-2 flex items-center justify-between border-b border-border">
                  <div className="flex items-center gap-2">
                    <Icon name="sort" size={12} className="text-muted cursor-grab" />
                    <div className="text-[13px] font-semibold">{sec.title}</div>
                  </div>
                  <div className="flex gap-1">
                    <button className="h-6 w-6 rounded hover:bg-slate-200 flex items-center justify-center text-muted">
                      <Icon name="edit" size={11} />
                    </button>
                    <button className="h-6 w-6 rounded hover:bg-slate-200 flex items-center justify-center text-muted">
                      <Icon name="trash" size={11} />
                    </button>
                  </div>
                </div>
                <div className="p-3 space-y-1.5">
                  {sec.fields.map((f, fi) => (
                    <div
                      key={fi}
                      className="flex items-center gap-2 px-2 py-1.5 rounded border border-border bg-white text-[12.5px]"
                    >
                      <Icon name="sort" size={11} className="text-slate-300 cursor-grab" />
                      <span className="font-medium">{f.label}</span>
                      {f.required && <Badge variant="red">requerido</Badge>}
                      <Badge variant="outline">{f.type}</Badge>
                      <div className="ml-auto flex gap-1">
                        <button className="h-6 w-6 rounded hover:bg-slate-100 flex items-center justify-center text-muted">
                          <Icon name="edit" size={11} />
                        </button>
                        <button className="h-6 w-6 rounded hover:bg-slate-100 flex items-center justify-center text-muted">
                          <Icon name="trash" size={11} />
                        </button>
                      </div>
                    </div>
                  ))}
                  <button className="w-full h-8 rounded border border-dashed border-slate-300 text-[12px] text-muted hover:border-amber hover:text-amber">
                    <Icon name="plus" size={11} className="inline mr-1" /> Agregar campo
                  </button>
                </div>
              </div>
            ))}
            <button className="w-full h-9 rounded border border-dashed border-slate-300 text-[12px] text-muted hover:border-amber hover:text-amber">
              <Icon name="plus" size={11} className="inline mr-1" /> Agregar sección
            </button>
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle>Mis plantillas</CardTitle>
          </CardHeader>
          <CardContent className="pt-0 space-y-2">
            {[
              { name: template.name, active: true, date: 'Actualizada hoy' },
              { name: 'Plantilla turno noche', active: false, date: '2026-03-10' },
              { name: 'Plantilla simplificada', active: false, date: '2026-02-21' },
            ].map((t, i) => (
              <div
                key={i}
                className={cn(
                  'flex items-center gap-3 px-3 py-2 rounded-md border',
                  t.active ? 'border-amber bg-amber-soft/30' : 'border-border bg-white',
                )}
              >
                <Icon name="file" size={14} className={t.active ? 'text-amber' : 'text-muted'} />
                <div className="flex-1 min-w-0">
                  <div className="text-[13px] font-medium truncate">{t.name}</div>
                  <div className="text-[10.5px] text-muted">{t.date}</div>
                </div>
                {t.active ? (
                  <Badge variant="amber">Activa</Badge>
                ) : (
                  <button className="text-[11px] text-amber hover:underline">Usar</button>
                )}
              </div>
            ))}
          </CardContent>
        </Card>
      </div>
    </div>
  );
}

// ---------- Template definitions ----------
function getTemplate(areaId) {
  const common = [
    { type: 'date', label: 'Fecha', key: 'date', required: true },
    {
      type: 'select',
      label: 'Turno',
      key: 'shift',
      options: ['Mañana', 'Tarde', 'Noche 00-06', 'Noche 18-24'],
      required: true,
    },
    { type: 'text', label: 'Autor', key: 'author', ph: 'Ej: V. Méndez', required: true },
  ];
  if (areaId === 'geologia') {
    return {
      name: 'Reporte de geología · estándar',
      sections: [
        { title: 'Identificación', fields: common },
        {
          title: 'Muestreo',
          description: 'Metadata de la muestra tomada en el turno.',
          fields: [
            { type: 'number', label: 'Profundidad muestra (m)', key: 'depth', required: true },
            { type: 'text', label: 'Formación', key: 'form', ph: 'Fm. Vaca Muerta' },
            {
              type: 'select',
              label: 'Litología principal',
              key: 'lit',
              options: ['Arenisca', 'Limolita', 'Calcárea', 'Arcilita', 'Shale'],
            },
            {
              type: 'select',
              label: 'Reactividad HCl 10%',
              key: 'hcl',
              options: ['Nula', 'Débil', 'Moderada', 'Fuerte'],
            },
          ],
        },
        {
          title: 'Observaciones',
          fields: [
            {
              type: 'textarea',
              label: 'Observaciones del geólogo',
              key: 'notes',
              full: true,
              ph: 'Descripción macroscópica, contenido fósil, anomalías…',
            },
          ],
        },
      ],
    };
  }
  if (areaId === 'fluidos') {
    return {
      name: 'Reporte físico-químico de fluido',
      sections: [
        { title: 'Identificación', fields: common },
        {
          title: 'Parámetros del fluido',
          fields: [
            { type: 'number', label: 'Densidad (g/cc)', key: 'dens' },
            { type: 'number', label: 'Viscosidad plástica (cP)', key: 'vp' },
            { type: 'number', label: 'Punto de cedencia', key: 'yp' },
            { type: 'number', label: 'pH', key: 'ph' },
            { type: 'number', label: 'Cloruros (ppm)', key: 'cl' },
            { type: 'number', label: 'Filtrado API (ml/30min)', key: 'filt' },
          ],
        },
        {
          title: 'Control de sólidos',
          fields: [
            {
              type: 'select',
              label: 'Estado de zaranda',
              key: 'shaker',
              options: ['OK', 'Reemplazar malla', 'Fuera de servicio'],
            },
            { type: 'number', label: '% sólidos', key: 'solids' },
            { type: 'textarea', label: 'Observaciones', key: 'notes', full: true },
          ],
        },
      ],
    };
  }
  if (areaId === 'hse') {
    return {
      name: 'Reporte HSE · diario',
      sections: [
        { title: 'Identificación', fields: common },
        {
          title: 'Clasificación',
          fields: [
            {
              type: 'select',
              label: 'Tipo',
              key: 'type',
              options: [
                'Observación conductual',
                'Incidente menor',
                'Derrame',
                'Near-miss',
                'Simulacro',
              ],
            },
            {
              type: 'select',
              label: 'Severidad',
              key: 'sev',
              options: ['Baja', 'Media', 'Alta', 'Crítica'],
            },
          ],
        },
        {
          title: 'Detalle',
          fields: [
            {
              type: 'textarea',
              label: 'Descripción del hecho',
              key: 'desc',
              full: true,
              required: true,
            },
            { type: 'textarea', label: 'Acciones tomadas', key: 'act', full: true },
            { type: 'text', label: 'Responsable seguimiento', key: 'owner' },
          ],
        },
      ],
    };
  }
  return { name: 'Plantilla', sections: [] };
}

// ---------- Program view ----------
function AreaProgramView({ area }) {
  return (
    <div className="view-in space-y-5">
      <div className="flex items-center justify-between flex-wrap gap-3">
        <div>
          <h2 className="text-[18px] font-bold tracking-tight">Programa · {area.label}</h2>
          <p className="text-[12px] text-muted mt-0.5">
            Pautas generales del programa de perforación para el equipo.
          </p>
        </div>
        <div className="flex gap-2">
          <Button variant="outline" size="sm">
            <Icon name="download" size={12} /> Descargar PDF
          </Button>
          <Button variant="primary" size="sm">
            <Icon name="upload" size={12} /> Subir nueva versión
          </Button>
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-5">
        <Card className="lg:col-span-2">
          <CardHeader>
            <div className="flex items-start justify-between">
              <div>
                <CardTitle>Programa vigente</CardTitle>
                <CardDescription>
                  Versión 3.2 · cargado el 2026-02-08 por Ing. R. Castro
                </CardDescription>
              </div>
              <Badge variant="emerald">Vigente</Badge>
            </div>
          </CardHeader>
          <CardContent className="pt-0">
            <div className="rounded-md border border-border bg-slate-50 h-[420px] flex items-center justify-center relative overflow-hidden">
              {/* PDF preview placeholder */}
              <div
                className="absolute inset-0 opacity-30"
                style={{
                  backgroundImage:
                    'repeating-linear-gradient(180deg, #E2E8F0 0, #E2E8F0 2px, transparent 2px, transparent 24px)',
                }}
              />
              <div className="relative bg-white border border-border shadow-pop rounded-sm w-56 aspect-[1/1.33] flex flex-col p-4">
                <div className="h-1 w-16 bg-amber rounded-full" />
                <div className="mt-2 text-[10px] font-bold uppercase tracking-wider">
                  {area.label}
                </div>
                <div className="text-[12px] font-bold mt-0.5">Programa de pozo · Rev 3.2</div>
                <div className="space-y-1 mt-3">
                  {[90, 75, 82, 70, 88, 65, 80, 72, 85, 78].map((w, i) => (
                    <div key={i} className="h-1 bg-slate-200 rounded" style={{ width: `${w}%` }} />
                  ))}
                </div>
                <div className="mt-auto flex items-center justify-between text-[8px] text-muted mono">
                  <span>OPTIMA · 02/2026</span>
                  <span>Pág. 1/24</span>
                </div>
              </div>
              <div className="absolute bottom-3 left-1/2 -translate-x-1/2 bg-white/90 backdrop-blur rounded-full border border-border px-3 py-1 text-[11px] text-muted">
                Click para abrir en lector
              </div>
            </div>
          </CardContent>
        </Card>

        <div className="space-y-4">
          <Card>
            <CardHeader>
              <CardTitle>Pautas clave</CardTitle>
            </CardHeader>
            <CardContent className="pt-0">
              <ul className="space-y-2.5 text-[13px]">
                {area.programHighlights.map((p, i) => (
                  <li key={i} className="flex gap-2.5 leading-snug">
                    <span className="mt-1.5 h-1.5 w-1.5 rounded-full bg-amber shrink-0" />
                    <span>{p}</span>
                  </li>
                ))}
              </ul>
            </CardContent>
          </Card>
          <Card>
            <CardHeader>
              <CardTitle>Historial de versiones</CardTitle>
            </CardHeader>
            <CardContent className="pt-0 space-y-2 text-[12.5px]">
              {[
                { v: '3.2', d: '2026-02-08', who: 'R. Castro', active: true },
                { v: '3.1', d: '2026-01-22', who: 'R. Castro' },
                { v: '3.0', d: '2025-12-15', who: 'M. Sosa' },
                { v: '2.4', d: '2025-11-03', who: 'M. Sosa' },
              ].map((v) => (
                <div
                  key={v.v}
                  className="flex items-center gap-3 py-1.5 border-b border-border last:border-b-0"
                >
                  <Icon name="file" size={13} className="text-muted" />
                  <div className="flex-1 min-w-0">
                    <div className="font-medium">
                      v{v.v}{' '}
                      {v.active && (
                        <Badge variant="emerald" className="ml-1">
                          actual
                        </Badge>
                      )}
                    </div>
                    <div className="text-[11px] text-muted">
                      {v.d} · {v.who}
                    </div>
                  </div>
                  <button className="text-[11px] text-amber hover:underline">Descargar</button>
                </div>
              ))}
            </CardContent>
          </Card>
        </div>
      </div>
    </div>
  );
}

// ---------- Shift handover ----------
function ShiftHandoverView({ area }) {
  const shifts = [
    {
      date: '2026-03-31',
      shift: 'Tarde',
      from: 'C. Godoy',
      to: 'L. Peralta',
      file: 'guardia-2026-03-31-T.pdf',
      size: '1.8 MB',
      summary: 'Avance 28 m · sin eventos mayores · próxima mecha en 4 hs.',
      status: 'leído',
    },
    {
      date: '2026-03-31',
      shift: 'Mañana',
      from: 'J. Pereyra',
      to: 'C. Godoy',
      file: 'guardia-2026-03-31-M.pdf',
      size: '2.1 MB',
      summary: 'Pico de presión 11:20 · ajustado caudal · operación normal.',
      status: 'leído',
    },
    {
      date: '2026-03-30',
      shift: 'Noche',
      from: 'A. Vera',
      to: 'J. Pereyra',
      file: 'guardia-2026-03-30-N.pdf',
      size: '1.6 MB',
      summary: 'Maniobra de limpieza · zaranda con recortes abundantes.',
      status: 'leído',
    },
    {
      date: '2026-03-30',
      shift: 'Tarde',
      from: 'C. Godoy',
      to: 'A. Vera',
      file: 'guardia-2026-03-30-T.pdf',
      size: '1.9 MB',
      summary: 'Avance 31 m · se cambió mecha 09:40.',
      status: 'leído',
    },
  ];
  const [selected, setSelected] = useState(shifts[0]);

  return (
    <div className="view-in space-y-5">
      <div className="flex items-center justify-between flex-wrap gap-3">
        <div>
          <h2 className="text-[18px] font-bold tracking-tight">Cambio de guardia · {area}</h2>
          <p className="text-[12px] text-muted mt-0.5">
            Quien está a cargo sube un reporte de su guardia para el próximo turno.
          </p>
        </div>
        <div className="flex gap-2">
          <Button variant="outline" size="sm">
            <Icon name="calendar" size={12} /> Calendario
          </Button>
          <Button variant="primary" size="sm">
            <Icon name="upload" size={12} /> Subir reporte de guardia
          </Button>
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-5 gap-5">
        {/* Upload + list */}
        <div className="lg:col-span-2 space-y-4">
          <Card>
            <CardContent className="pt-5">
              <div className="rounded-lg border-2 border-dashed border-slate-200 bg-slate-50/60 p-5 text-center hover:border-amber transition cursor-pointer">
                <div className="mx-auto h-10 w-10 rounded-full bg-amber-soft text-amber-ink flex items-center justify-center mb-2">
                  <Icon name="upload" size={16} />
                </div>
                <div className="text-[13px] font-semibold">Subir reporte (PDF)</div>
                <div className="text-[11.5px] text-muted mt-1">
                  Arrastrá el archivo o click para elegir
                </div>
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardHeader>
              <CardTitle>Últimas guardias</CardTitle>
            </CardHeader>
            <div className="pb-2">
              {shifts.map((s, i) => (
                <button
                  key={i}
                  onClick={() => setSelected(s)}
                  className={cn(
                    'w-full text-left px-5 py-3 border-t border-border flex items-start gap-3 hover:bg-slate-50/70',
                    selected === s && 'bg-amber-soft/30',
                  )}
                >
                  <div
                    className={cn(
                      'mt-1 h-8 w-8 rounded-md flex items-center justify-center shrink-0',
                      selected === s ? 'bg-amber text-white' : 'bg-slate-100 text-muted',
                    )}
                  >
                    <Icon name="file" size={14} />
                  </div>
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-2">
                      <div className="text-[13px] font-semibold">{s.date}</div>
                      <Badge variant="outline">{s.shift}</Badge>
                    </div>
                    <div className="text-[11.5px] text-muted mt-0.5">
                      {s.from} → {s.to}
                    </div>
                    <div className="text-[12px] text-ink mt-1 leading-snug line-clamp-2">
                      {s.summary}
                    </div>
                  </div>
                </button>
              ))}
            </div>
          </Card>
        </div>

        {/* Reader */}
        <div className="lg:col-span-3">
          <Card>
            <CardHeader>
              <div className="flex items-start justify-between">
                <div>
                  <CardTitle>
                    Reporte de guardia · {selected.date} · {selected.shift}
                  </CardTitle>
                  <CardDescription>
                    Entregada por <b className="text-ink">{selected.from}</b> · recibida por{' '}
                    <b className="text-ink">{selected.to}</b>
                  </CardDescription>
                </div>
                <div className="flex gap-2">
                  <Button variant="outline" size="sm">
                    <Icon name="download" size={12} /> Descargar
                  </Button>
                </div>
              </div>
            </CardHeader>
            <CardContent className="pt-0">
              <div className="rounded-md border border-border bg-slate-50 h-[420px] flex items-center justify-center relative overflow-hidden">
                <div
                  className="absolute inset-0 opacity-30"
                  style={{
                    backgroundImage:
                      'repeating-linear-gradient(180deg, #E2E8F0 0, #E2E8F0 2px, transparent 2px, transparent 24px)',
                  }}
                />
                <div className="relative bg-white border border-border shadow-pop rounded-sm w-72 aspect-[1/1.33] flex flex-col p-5">
                  <div className="text-[9px] font-bold uppercase tracking-wider text-amber">
                    OPTIMA · {area}
                  </div>
                  <div className="text-[13px] font-bold mt-1">Cambio de guardia</div>
                  <div className="text-[10px] text-muted mt-0.5 mono">{selected.file}</div>
                  <div className="h-px bg-border my-3" />
                  <div className="text-[10px] font-semibold uppercase tracking-wider text-muted">
                    Resumen
                  </div>
                  <div className="text-[10.5px] leading-relaxed text-slate-600 mt-1">
                    {selected.summary}
                  </div>
                  <div className="space-y-1 mt-4">
                    {[88, 72, 80, 65, 55, 78, 70, 82, 60, 74, 80].map((w, i) => (
                      <div
                        key={i}
                        className="h-1 bg-slate-200 rounded"
                        style={{ width: `${w}%` }}
                      />
                    ))}
                  </div>
                  <div className="mt-auto flex items-center justify-between text-[8px] text-muted mono">
                    <span>{selected.size}</span>
                    <span>Pág. 1/3</span>
                  </div>
                </div>
              </div>
            </CardContent>
          </Card>
        </div>
      </div>
    </div>
  );
}

// ---------- Programa de pozo gral (top-level module) ----------
function ProgramaPozoModule() {
  return (
    <div className="view-in space-y-5">
      <div className="flex items-center justify-between flex-wrap gap-3">
        <div>
          <h2 className="text-[18px] font-bold tracking-tight">Programa de pozo general</h2>
          <p className="text-[12px] text-muted mt-0.5">
            Pautas de perforación · archivo de lectura. Subí un PDF y cualquier usuario puede
            consultarlo.
          </p>
        </div>
        <div className="flex gap-2">
          <Button variant="outline" size="sm">
            <Icon name="download" size={12} /> Descargar
          </Button>
          <Button variant="primary" size="sm">
            <Icon name="upload" size={12} /> Subir nueva versión
          </Button>
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-4 gap-5">
        <Card className="lg:col-span-3">
          <CardContent className="pt-5">
            <div className="rounded-md border border-border bg-slate-50 h-[560px] flex items-center justify-center relative overflow-hidden">
              <div
                className="absolute inset-0 opacity-25"
                style={{
                  backgroundImage:
                    'repeating-linear-gradient(180deg, #E2E8F0 0, #E2E8F0 2px, transparent 2px, transparent 24px)',
                }}
              />
              <div className="relative bg-white border border-border shadow-pop rounded-sm w-80 aspect-[1/1.33] flex flex-col p-6">
                <div className="h-1 w-20 bg-amber rounded-full" />
                <div className="mt-3 text-[10px] font-bold uppercase tracking-wider text-muted">
                  OPTIMA DRILLING
                </div>
                <div className="text-[15px] font-extrabold mt-0.5">Programa de pozo general</div>
                <div className="text-[11px] text-muted mt-0.5 mono">NETTO-4H · Rev 3.2</div>
                <div className="h-px bg-border my-4" />
                <div className="space-y-1.5">
                  {[92, 76, 84, 70, 88, 65, 80, 72, 85, 78, 68, 82, 74, 86, 70].map((w, i) => (
                    <div key={i} className="h-1 bg-slate-200 rounded" style={{ width: `${w}%` }} />
                  ))}
                </div>
                <div className="mt-auto flex items-center justify-between text-[9px] text-muted mono">
                  <span>2026-02-08 · R. Castro</span>
                  <span>Pág. 1/34</span>
                </div>
              </div>

              {/* Toolbar */}
              <div className="absolute bottom-3 left-1/2 -translate-x-1/2 bg-white/95 backdrop-blur rounded-full border border-border shadow-card px-2 py-1 text-[11px] text-muted flex items-center gap-1">
                <button className="h-7 w-7 rounded-full hover:bg-slate-100 flex items-center justify-center">
                  <Icon name="chevronRight" size={12} className="rotate-180" />
                </button>
                <span className="px-2 tnum">
                  <b className="text-ink">1</b> / 34
                </span>
                <button className="h-7 w-7 rounded-full hover:bg-slate-100 flex items-center justify-center">
                  <Icon name="chevronRight" size={12} />
                </button>
                <div className="w-px h-5 bg-border mx-1" />
                <button className="h-7 px-2 rounded-full hover:bg-slate-100 text-[11px]">
                  100%
                </button>
                <button className="h-7 w-7 rounded-full hover:bg-slate-100 flex items-center justify-center">
                  <Icon name="download" size={12} />
                </button>
              </div>
            </div>
          </CardContent>
        </Card>

        <div className="space-y-4">
          <Card>
            <CardHeader>
              <CardTitle>Documento</CardTitle>
            </CardHeader>
            <CardContent className="pt-0 space-y-2.5 text-[12.5px]">
              <div className="flex justify-between">
                <span className="text-muted">Archivo</span>
                <span className="font-medium mono text-[11px]">programa-netto4h-v32.pdf</span>
              </div>
              <div className="flex justify-between">
                <span className="text-muted">Tamaño</span>
                <span className="font-medium tnum">4.2 MB</span>
              </div>
              <div className="flex justify-between">
                <span className="text-muted">Páginas</span>
                <span className="font-medium tnum">34</span>
              </div>
              <div className="flex justify-between">
                <span className="text-muted">Versión</span>
                <span className="font-medium">
                  3.2{' '}
                  <Badge variant="emerald" className="ml-1">
                    vigente
                  </Badge>
                </span>
              </div>
              <div className="flex justify-between">
                <span className="text-muted">Subido</span>
                <span className="font-medium tnum">2026-02-08</span>
              </div>
              <div className="flex justify-between">
                <span className="text-muted">Por</span>
                <span className="font-medium">R. Castro</span>
              </div>
            </CardContent>
          </Card>
          <Card>
            <CardHeader>
              <CardTitle>Historial</CardTitle>
            </CardHeader>
            <CardContent className="pt-0 space-y-2 text-[12.5px]">
              {[
                { v: '3.2', d: '2026-02-08', who: 'R. Castro', active: true },
                { v: '3.1', d: '2026-01-15', who: 'R. Castro' },
                { v: '3.0', d: '2025-12-08', who: 'M. Sosa' },
              ].map((v) => (
                <div
                  key={v.v}
                  className="flex items-center gap-3 py-1.5 border-b border-border last:border-b-0"
                >
                  <Icon name="file" size={13} className="text-muted" />
                  <div className="flex-1 min-w-0">
                    <div className="font-medium">
                      v{v.v}{' '}
                      {v.active && (
                        <Badge variant="emerald" className="ml-1">
                          actual
                        </Badge>
                      )}
                    </div>
                    <div className="text-[11px] text-muted">
                      {v.d} · {v.who}
                    </div>
                  </div>
                </div>
              ))}
            </CardContent>
          </Card>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { AreaModule, AREAS, ShiftHandoverView, ProgramaPozoModule });
