const { useState, useEffect } = React;

// ─── Mobile Activity Row ──────────────────────────────────────────────────────
function ActivityRow({ act, onUpdate }) {
  const [realPct, setRealPct] = useState(act.planned - 8);
  const [qty, setQty] = useState(0);
  const [hh, setHH] = useState(0);
  const deviation = realPct - act.planned;
  const devColor = deviation >= 0 ? C.success : deviation > -10 ? C.warning : C.danger;

  return (
    <div style={{ background:'#fff', borderRadius:10, padding:'12px 14px', marginBottom:8, border:`1px solid ${C.border}`, boxShadow:'0 1px 3px rgba(0,0,0,0.06)' }}>
      <div style={{ display:'flex', justifyContent:'space-between', alignItems:'flex-start', marginBottom:6 }}>
        <div style={{ flex:1 }}>
          <div style={{ fontSize:10, fontFamily:'IBM Plex Mono, monospace', color:C.primary, fontWeight:700, marginBottom:1 }}>{act.wbs}</div>
          <div style={{ fontSize:12, fontWeight:600, color:C.text, lineHeight:1.3 }}>{act.desc}</div>
        </div>
        <div style={{ textAlign:'right', marginLeft:8 }}>
          <div style={{ fontSize:10, color:C.textSub }}>Plano: {act.planned}%</div>
          <div style={{ fontSize:13, fontWeight:800, color:devColor }}>{realPct}%</div>
        </div>
      </div>

      {/* Progress bar */}
      <div style={{ position:'relative', height:10, background:'#F1F5F9', borderRadius:4, marginBottom:8, overflow:'hidden' }}>
        <div style={{ position:'absolute', top:0, left:0, width:`${act.planned}%`, height:'100%', background:'#CBD5E1', borderRadius:4 }} />
        <div style={{ position:'absolute', top:2, left:0, width:`${Math.min(100,realPct)}%`, height:6, background:devColor, borderRadius:3, transition:'width 0.2s' }} />
      </div>

      {/* Controls */}
      <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr 1fr', gap:6, marginBottom:6 }}>
        <div>
          <div style={{ fontSize:9.5, color:C.textSub, marginBottom:2, fontWeight:600 }}>% REAL</div>
          <input type="number" value={realPct} min={0} max={100}
            onChange={e => setRealPct(Number(e.target.value))}
            style={{ width:'100%', padding:'6px 8px', border:`1px solid ${devColor}66`, borderRadius:5, fontSize:13, fontWeight:700, fontFamily:'inherit', textAlign:'center', boxSizing:'border-box', color:devColor }} />
        </div>
        <div>
          <div style={{ fontSize:9.5, color:C.textSub, marginBottom:2, fontWeight:600 }}>QTD ({act.unit})</div>
          <input type="number" value={qty} min={0}
            onChange={e => setQty(Number(e.target.value))}
            style={{ width:'100%', padding:'6px 8px', border:`1px solid ${C.border}`, borderRadius:5, fontSize:13, fontFamily:'inherit', textAlign:'center', boxSizing:'border-box' }} />
        </div>
        <div>
          <div style={{ fontSize:9.5, color:C.textSub, marginBottom:2, fontWeight:600 }}>HH (hrs)</div>
          <input type="number" value={hh} min={0}
            onChange={e => setHH(Number(e.target.value))}
            style={{ width:'100%', padding:'6px 8px', border:`1px solid ${C.border}`, borderRadius:5, fontSize:13, fontFamily:'inherit', textAlign:'center', boxSizing:'border-box' }} />
        </div>
      </div>

      {deviation < -10 && (
        <div style={{ fontSize:10.5, color:C.danger, fontWeight:600, background:'#FFF5F5', padding:'4px 8px', borderRadius:4 }}>
          ⚠ Desvio de {Math.abs(deviation.toFixed(0))}pp abaixo do plano — justificativa requerida ao salvar
        </div>
      )}
    </div>
  );
}

// ─── Occurrence buttons ───────────────────────────────────────────────────────
function OccurrenceSection() {
  const [selected, setSelected] = useState(null);
  const [text, setText] = useState('');

  const types = [
    { id:'rain',    label:'🌧 Chuva',       color:'#3B82F6' },
    { id:'stop',    label:'🛑 Paralisação', color:C.danger  },
    { id:'accident',label:'⛑ Acidente',    color:'#F97316' },
    { id:'ncq',     label:'❌ NCQ',         color:C.warning },
    { id:'env',     label:'🌿 Ambiental',   color:C.success },
  ];

  return (
    <div style={{ background:'#fff', borderRadius:10, padding:'12px 14px', marginBottom:8, border:`1px solid ${C.border}` }}>
      <div style={{ fontSize:12, fontWeight:700, color:C.text, marginBottom:8 }}>Registro de Ocorrência</div>
      <div style={{ display:'flex', flexWrap:'wrap', gap:6, marginBottom:8 }}>
        {types.map(t => (
          <button key={t.id} onClick={() => setSelected(selected === t.id ? null : t.id)}
            style={{ padding:'6px 10px', fontSize:11, fontWeight:600, border:`1.5px solid ${selected===t.id?t.color:C.border}`, borderRadius:6, background: selected===t.id ? `${t.color}18` : '#F8FAFC', color: selected===t.id ? t.color : C.textSub, cursor:'pointer', fontFamily:'inherit' }}>
            {t.label}
          </button>
        ))}
      </div>
      {selected && (
        <>
          <textarea value={text} onChange={e => setText(e.target.value)} placeholder="Descreva a ocorrência, local e impacto estimado..."
            style={{ width:'100%', padding:'8px 10px', border:`1px solid ${C.border}`, borderRadius:6, fontSize:12, fontFamily:'inherit', resize:'none', height:70, boxSizing:'border-box', marginBottom:6 }} />
          <div style={{ display:'flex', gap:6 }}>
            <button style={{ flex:1, padding:'7px', fontSize:11, fontWeight:700, background:'#F8FAFC', border:`1px solid ${C.border}`, borderRadius:6, cursor:'pointer', fontFamily:'inherit', color:C.text }}>
              📷 Foto + GPS
            </button>
            <button onClick={() => { setSelected(null); setText(''); alert('Ocorrência registrada!'); }}
              style={{ flex:1, padding:'7px', fontSize:11, fontWeight:700, background:C.warning, border:'none', borderRadius:6, cursor:'pointer', fontFamily:'inherit', color:'#fff' }}>
              Registrar
            </button>
          </div>
        </>
      )}
    </div>
  );
}

// ─── New Requisition ─────────────────────────────────────────────────────────
function RequisitionSection() {
  const [open, setOpen] = useState(false);
  const [urgent, setUrgent] = useState(false);
  const [item, setItem] = useState('');
  const [value, setValue] = useState('');

  return (
    <div style={{ background:'#fff', borderRadius:10, padding:'12px 14px', marginBottom:8, border:`1px solid ${C.border}` }}>
      <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom: open ? 10 : 0 }}>
        <div style={{ fontSize:12, fontWeight:700, color:C.text }}>Nova Requisição de Pedido</div>
        <button onClick={() => setOpen(o => !o)} style={{ fontSize:11, fontWeight:700, padding:'5px 10px', background: open ? C.borderSub : C.primary, color: open ? C.text : '#fff', border:'none', borderRadius:5, cursor:'pointer', fontFamily:'inherit' }}>
          {open ? '— Fechar' : '+ Nova Req.'}
        </button>
      </div>
      {open && (
        <>
          <div style={{ marginBottom:6 }}>
            <div style={{ fontSize:10, color:C.textSub, fontWeight:600, marginBottom:2 }}>ITEM / ESPECIFICAÇÃO</div>
            <input value={item} onChange={e => setItem(e.target.value)} placeholder="Ex: Concreto FCK30, 20m³"
              style={{ width:'100%', padding:'7px 10px', border:`1px solid ${C.border}`, borderRadius:5, fontSize:12, fontFamily:'inherit', boxSizing:'border-box' }} />
          </div>
          <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:6, marginBottom:6 }}>
            <div>
              <div style={{ fontSize:10, color:C.textSub, fontWeight:600, marginBottom:2 }}>VALOR ESTIMADO</div>
              <input value={value} onChange={e => setValue(e.target.value)} placeholder="R$ 0,00"
                style={{ width:'100%', padding:'7px 10px', border:`1px solid ${C.border}`, borderRadius:5, fontSize:12, fontFamily:'inherit', boxSizing:'border-box' }} />
            </div>
            <div>
              <div style={{ fontSize:10, color:C.textSub, fontWeight:600, marginBottom:2 }}>WBS</div>
              <select style={{ width:'100%', padding:'7px 10px', border:`1px solid ${C.border}`, borderRadius:5, fontSize:12, fontFamily:'inherit', boxSizing:'border-box', background:'#fff' }}>
                <option>1.3.2.3 — Concretagem</option>
                <option>1.3.2.4 — Armação</option>
                <option>1.4.1.2 — Estrutura Met.</option>
                <option>2.1.1.3 — Equipamentos</option>
              </select>
            </div>
          </div>
          <div style={{ display:'flex', alignItems:'center', gap:8, marginBottom:8 }}>
            <input type="checkbox" id="urgent-check" checked={urgent} onChange={e => setUrgent(e.target.checked)} />
            <label htmlFor="urgent-check" style={{ fontSize:12, fontWeight:600, color:urgent?C.danger:C.text, cursor:'pointer' }}>
              {urgent ? '🚨 URGENTE — SLA 2h' : 'Marcar como urgente'}
            </label>
          </div>
          <div style={{ padding:'6px 10px', background:'#F0F6FF', borderRadius:5, fontSize:11, color:C.primary, marginBottom:8 }}>
            <strong>Saldo WBS 1.3.2.3:</strong> R$ 42.000 disponível
          </div>
          <button onClick={() => { alert('Requisição REQ-2853 criada e enviada para aprovação!'); setOpen(false); setItem(''); setValue(''); }}
            style={{ width:'100%', padding:'10px', fontSize:13, fontWeight:700, background:C.primary, color:'#fff', border:'none', borderRadius:7, cursor:'pointer', fontFamily:'inherit' }}>
            Criar Requisição
          </button>
        </>
      )}
    </div>
  );
}

// ─── Labor Counter ────────────────────────────────────────────────────────────
function LaborCounter() {
  const [counts, setCounts] = useState({ Pedreiro:8, Servente:12, Operador:3, Armador:5, Eletricista:2, Encarregado:1 });
  const total = Object.values(counts).reduce((s,v) => s+v, 0);

  return (
    <div style={{ background:'#fff', borderRadius:10, padding:'12px 14px', marginBottom:8, border:`1px solid ${C.border}` }}>
      <div style={{ display:'flex', justifyContent:'space-between', marginBottom:8 }}>
        <div style={{ fontSize:12, fontWeight:700, color:C.text }}>Efetivo em Campo</div>
        <div style={{ fontSize:13, fontWeight:800, color:C.primary }}>{total} colaboradores</div>
      </div>
      <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:6 }}>
        {Object.entries(counts).map(([role, count]) => (
          <div key={role} style={{ display:'flex', alignItems:'center', gap:6, background:'#F8FAFC', borderRadius:6, padding:'6px 8px' }}>
            <span style={{ flex:1, fontSize:11.5, color:C.text, fontWeight:500 }}>{role}</span>
            <button onClick={() => setCounts(c => ({ ...c, [role]: Math.max(0,c[role]-1) }))}
              style={{ width:22, height:22, borderRadius:4, border:`1px solid ${C.border}`, background:'#fff', cursor:'pointer', fontSize:13, fontWeight:700, display:'flex', alignItems:'center', justifyContent:'center', color:C.textSub }}>−</button>
            <span style={{ width:22, textAlign:'center', fontSize:13, fontWeight:700, color:C.text }}>{count}</span>
            <button onClick={() => setCounts(c => ({ ...c, [role]: c[role]+1 }))}
              style={{ width:22, height:22, borderRadius:4, border:`1px solid ${C.primary}`, background:C.primary, cursor:'pointer', fontSize:13, fontWeight:700, display:'flex', alignItems:'center', justifyContent:'center', color:'#fff' }}>+</button>
          </div>
        ))}
      </div>
    </div>
  );
}

// ─── Screen 8: SED — Campo Mobile ────────────────────────────────────────────
function Screen8SED() {
  const { sedActivities } = window.SIGP_DATA;
  const [saved, setSaved] = useState(false);
  const [offline, setOffline] = useState(false);
  const [pending, setPending] = useState(0);

  function handleSave() {
    if (offline) { setPending(p => p+1); alert('Dados salvos localmente. Sincronização pendente quando voltar online.'); }
    else { setSaved(true); setTimeout(() => setSaved(false), 3000); alert('Avanço físico registrado com sucesso! Dados sincronizados com o SIGP.'); }
  }

  return (
    <div style={{ display:'flex', justifyContent:'center', alignItems:'flex-start', padding:'24px 20px', minHeight:'100%', background:'#E5E7EB' }}>
      {/* Phone frame */}
      <div style={{ width:390, background:'#F0F2F5', borderRadius:36, boxShadow:'0 20px 60px rgba(0,0,0,0.3), 0 0 0 10px #1C1C1E', overflow:'hidden', maxHeight:'calc(100vh - 180px)', display:'flex', flexDirection:'column', position:'relative' }}>

        {/* Status bar */}
        <div style={{ background:C.sidebar, padding:'10px 20px 6px', display:'flex', justifyContent:'space-between', alignItems:'center' }}>
          <span style={{ color:'#fff', fontSize:12, fontWeight:700 }}>09:47</span>
          <div style={{ display:'flex', gap:6, alignItems:'center' }}>
            {offline ? (
              <span style={{ fontSize:10, background:C.warning, color:'#fff', padding:'2px 7px', borderRadius:8, fontWeight:700 }}>
                📡 OFFLINE{pending>0?` · ${pending} pendente${pending>1?'s':''}` :''}
              </span>
            ) : (
              <span style={{ fontSize:10, color:'rgba(255,255,255,0.7)' }}>● Online</span>
            )}
            <span style={{ color:'rgba(255,255,255,0.7)', fontSize:11 }}>📶 🔋</span>
          </div>
        </div>

        {/* App header */}
        <div style={{ background:C.primary, padding:'10px 16px 12px' }}>
          <div style={{ display:'flex', justifyContent:'space-between', alignItems:'flex-start' }}>
            <div>
              <div style={{ fontSize:11, color:'rgba(255,255,255,0.7)', fontWeight:600 }}>SED — Sistema de Entrada de Dados</div>
              <div style={{ fontSize:14.5, color:'#fff', fontWeight:800, lineHeight:1.2 }}>Construtora Pioneira S/A</div>
            </div>
            <div style={{ textAlign:'right' }}>
              <div style={{ fontSize:10.5, color:'rgba(255,255,255,0.8)' }}>Eng. Roberto Lima</div>
              <div style={{ fontSize:10, color:'rgba(255,255,255,0.6)' }}>Ger. Civil · Canteiro A</div>
            </div>
          </div>
          <div style={{ marginTop:8, display:'flex', justifyContent:'space-between', alignItems:'center' }}>
            <span style={{ fontSize:11, color:'rgba(255,255,255,0.8)' }}>📅 23/05/2026 · Semana 8</span>
            <button onClick={() => setOffline(o => !o)} style={{ fontSize:10, padding:'3px 8px', background:'rgba(255,255,255,0.15)', border:'1px solid rgba(255,255,255,0.3)', borderRadius:5, color:'#fff', cursor:'pointer', fontFamily:'inherit', fontWeight:600 }}>
              {offline ? '🔴 Simular Online' : '📡 Simular Offline'}
            </button>
          </div>
        </div>

        {/* Scrollable content */}
        <div style={{ flex:1, overflowY:'auto', padding:'12px 12px 0' }}>

          {/* Section: Avanço físico */}
          <div style={{ fontSize:11, fontWeight:800, color:C.textSub, letterSpacing:0.8, textTransform:'uppercase', marginBottom:8 }}>Avanço Físico do Dia</div>
          {sedActivities.map((act, i) => (
            <ActivityRow key={i} act={act} onUpdate={() => {}} />
          ))}

          {/* Occurrence */}
          <div style={{ fontSize:11, fontWeight:800, color:C.textSub, letterSpacing:0.8, textTransform:'uppercase', marginBottom:8, marginTop:4 }}>Ocorrências</div>
          <OccurrenceSection />

          {/* Requisition */}
          <div style={{ fontSize:11, fontWeight:800, color:C.textSub, letterSpacing:0.8, textTransform:'uppercase', marginBottom:8 }}>Suprimentos</div>
          <RequisitionSection />

          {/* Labor */}
          <div style={{ fontSize:11, fontWeight:800, color:C.textSub, letterSpacing:0.8, textTransform:'uppercase', marginBottom:8 }}>Efetivo e Equipamentos</div>
          <LaborCounter />

          {/* Equipment */}
          <div style={{ background:'#fff', borderRadius:10, padding:'12px 14px', marginBottom:12, border:`1px solid ${C.border}` }}>
            <div style={{ fontSize:12, fontWeight:700, color:C.text, marginBottom:8 }}>Equipamentos em Operação</div>
            {[['Betoneira 600L','Ligada'],['Retroescavadeira CAT','Ligada'],['Vibrador de concreto','Ligado'],['Guindaste 25t','Parado — manutenção']].map(([eq,st]) => (
              <div key={eq} style={{ display:'flex', justifyContent:'space-between', padding:'5px 0', borderBottom:`1px solid ${C.borderSub}`, fontSize:12 }}>
                <span style={{ color:C.text }}>{eq}</span>
                <span style={{ color: st.includes('Parado') ? C.warning : C.success, fontWeight:600, fontSize:11 }}>{st}</span>
              </div>
            ))}
          </div>

          <div style={{ height:100 }} />
        </div>

        {/* Save button — sticky bottom */}
        <div style={{ padding:'10px 12px 16px', background:'#F0F2F5', borderTop:`1px solid ${C.border}` }}>
          {saved && (
            <div style={{ marginBottom:6, padding:'6px 10px', background:'#DCFCE7', borderRadius:6, fontSize:11, fontWeight:700, color:'#065F46', textAlign:'center' }}>
              ✓ Dados sincronizados com sucesso!
            </div>
          )}
          <button onClick={handleSave} style={{
            width:'100%', padding:'13px', fontSize:14, fontWeight:800,
            background: offline ? C.warning : C.success,
            color:'#fff', border:'none', borderRadius:10, cursor:'pointer', fontFamily:'inherit',
            boxShadow:`0 4px 12px ${offline ? C.warning : C.success}66`,
          }}>
            {offline ? '💾 Salvar Localmente (Offline)' : '✓ Salvar e Sincronizar'}
          </button>
          <div style={{ textAlign:'center', fontSize:10, color:C.textSub, marginTop:4 }}>
            {offline ? `${pending} registro(s) pendente(s) de sincronização` : 'Dados enviados ao SIGP em tempo real'}
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Screen8SED });
