// ===== Notificaciones: plantillas + bitácora =====
function Notificaciones({ notifications, templates, setTemplates, orders }){
  const [tab, setTab] = React.useState("bitacora");
  const sent = notifications.length;
  const log = [...notifications].sort((a,b)=> new Date(b.t)-new Date(a.t));

  function toggleAuto(id){ setTemplates(prev => prev.map(t => t.id===id ? { ...t, auto:!t.auto } : t)); }
  function setChannel(id, ch){ setTemplates(prev => prev.map(t => t.id===id ? { ...t, channel:ch } : t)); }
  function setBody(id, body){ setTemplates(prev => prev.map(t => t.id===id ? { ...t, body } : t)); }

  return (
    <div style={{ display:"flex", flexDirection:"column", gap:16, animation:"fadeUp .35s ease" }}>
      {/* note about demo */}
      <Card pad={14} style={{ background:"var(--st-entrada-soft)", borderColor:"oklch(0.86 0.07 75)" }}>
        <div style={{ display:"flex", alignItems:"flex-start", gap:10 }}>
          <Icon name="warning" size={18} style={{ color:"var(--st-entrada)", flexShrink:0, marginTop:1 }} />
          <div style={{ fontSize:12.5, color:"var(--ink-2)", lineHeight:1.5 }}>
            <strong style={{ color:"var(--st-entrada)" }}>Modo demostración:</strong> los mensajes se registran y previsualizan aquí. El envío real por Email y WhatsApp se activa al conectar el sistema con un proveedor (requiere publicar el sistema con servidor).
          </div>
        </div>
      </Card>

      {/* summary */}
      <div style={{ display:"grid", gridTemplateColumns:"repeat(3,1fr)", gap:14 }}>
        <SumCard icon="sms" hue={256} value={sent} label="Mensajes enviados" sub="histórico" />
        <SumCard icon="whatsapp" hue={155} value={notifications.filter(n=>n.channel!=="email").length} label="Por WhatsApp" sub="incluye combinados" />
        <SumCard icon="settings" hue={70} value={templates.filter(t=>t.auto).length} label="Avisos automáticos" sub={`de ${templates.length} plantillas`} />
      </div>

      <Card pad={0}>
        <div style={{ display:"flex", gap:4, padding:"6px 8px", borderBottom:"1px solid var(--line)" }}>
          {[["bitacora","Bitácora de envíos"],["plantillas","Plantillas y automatización"]].map(([id,l])=>{
            const active = tab===id;
            return (
              <button key={id} onClick={()=>setTab(id)} style={{ padding:"10px 16px", border:"none", background:"transparent", borderRadius:9,
                fontSize:14, fontWeight: active?700:600, color: active?"var(--accent-ink)":"var(--muted)", position:"relative" }}>
                {l}
                {active && <span style={{ position:"absolute", left:12, right:12, bottom:-7, height:3, borderRadius:99, background:"var(--accent)" }} />}
              </button>
            );
          })}
        </div>

        {tab==="bitacora" ? (
          <div>
            {log.map((n,i)=>(
              <div key={n.id} style={{ display:"flex", alignItems:"flex-start", gap:13, padding:"14px 20px", borderBottom: i<log.length-1?"1px solid var(--line-2)":"none" }}>
                <ChannelIcon channel={n.channel} />
                <div style={{ flex:1, minWidth:0 }}>
                  <div style={{ display:"flex", alignItems:"center", gap:8, flexWrap:"wrap" }}>
                    <span style={{ fontSize:13.5, fontWeight:700 }}>{n.clientName}</span>
                    <span className="mono" style={{ fontSize:12, color:"var(--accent-ink)" }}>#{n.orderNum}</span>
                    <span style={{ fontSize:11.5, fontWeight:600, color:"var(--st-listo)", background:"var(--st-listo-soft)", padding:"2px 8px", borderRadius:99 }}>Enviado</span>
                  </div>
                  <div style={{ fontSize:13, color:"var(--ink-2)", marginTop:4, lineHeight:1.5 }}>{n.preview}</div>
                </div>
                <span style={{ fontSize:12, color:"var(--faint)", whiteSpace:"nowrap" }}>{relTime(n.t)}</span>
              </div>
            ))}
            {log.length===0 && <div style={{ padding:48, textAlign:"center", color:"var(--faint)" }}>Aún no se han enviado notificaciones.</div>}
          </div>
        ) : (
          <div style={{ padding:16, display:"flex", flexDirection:"column", gap:12 }}>
            {templates.map(t=>(
              <div key={t.id} style={{ border:"1px solid var(--line)", borderRadius:12, padding:16 }}>
                <div style={{ display:"flex", alignItems:"center", justifyContent:"space-between", gap:12, marginBottom:12, flexWrap:"wrap" }}>
                  <div style={{ display:"flex", alignItems:"center", gap:10 }}>
                    <span style={{ width:34, height:34, borderRadius:9, background:"var(--accent-soft)", color:"var(--accent-ink)", display:"flex", alignItems:"center", justifyContent:"center" }}><Icon name="sms" size={18} /></span>
                    <div>
                      <div style={{ fontSize:14.5, fontWeight:700 }}>{t.label}</div>
                      <div style={{ fontSize:12, color:"var(--muted)" }}>Se sugiere al pasar a "{STATUSES[t.trigger]?.label || t.trigger}"</div>
                    </div>
                  </div>
                  <label style={{ display:"flex", alignItems:"center", gap:9, fontSize:12.5, fontWeight:600, color:"var(--ink-2)" }}>
                    Envío automático
                    <button onClick={()=>toggleAuto(t.id)} style={{ width:42, height:24, borderRadius:99, border:"none", padding:2, cursor:"pointer",
                      background: t.auto?"var(--accent)":"var(--line)", transition:"background .2s", display:"flex", justifyContent: t.auto?"flex-end":"flex-start" }}>
                      <span style={{ width:20, height:20, borderRadius:"50%", background:"#fff", boxShadow:"var(--shadow-sm)" }} />
                    </button>
                  </label>
                </div>

                <div style={{ display:"flex", gap:7, marginBottom:10 }}>
                  {[["email","Email","sms"],["whatsapp","WhatsApp","whatsapp"],["both","Ambos","bell"]].map(([id,l,ic])=>{
                    const sel = t.channel===id;
                    return (
                      <button key={id} onClick={()=>setChannel(t.id,id)} style={{ display:"inline-flex", alignItems:"center", gap:6, padding:"6px 12px", borderRadius:8, fontSize:12.5, fontWeight:600, cursor:"pointer",
                        border:`1px solid ${sel?"var(--accent)":"var(--line)"}`, background: sel?"var(--accent-soft)":"var(--surface)", color: sel?"var(--accent-ink)":"var(--ink-2)" }}>
                        <Icon name={ic} size={14} /> {l}
                      </button>
                    );
                  })}
                </div>

                <textarea value={t.body} onChange={e=>setBody(t.id, e.target.value)} rows={2}
                  style={{ ...inputStyle, resize:"vertical", lineHeight:1.5, fontSize:13 }} />
                <div style={{ fontSize:11.5, color:"var(--faint)", marginTop:7 }}>
                  Variables: <code style={{ fontFamily:"var(--mono)" }}>{"{cliente} {equipo} {num} {presupuesto} {saldo}"}</code>
                </div>
              </div>
            ))}
          </div>
        )}
      </Card>
    </div>
  );
}

function ChannelIcon({ channel, size=36 }){
  const map = {
    email:    { ic:"sms",      hue:256 },
    whatsapp: { ic:"whatsapp", hue:155 },
    both:     { ic:"bell",     hue:70 },
  }[channel] || { ic:"sms", hue:256 };
  return (
    <span style={{ width:size, height:size, borderRadius:10, flexShrink:0, display:"flex", alignItems:"center", justifyContent:"center",
      background:`oklch(0.95 0.04 ${map.hue})`, color:`oklch(0.5 0.13 ${map.hue})` }}><Icon name={map.ic} size={size*0.5} /></span>
  );
}

// ===== Modal: avisar al cliente desde una orden =====
function NotifyModal({ order, templates, onSend, onClose }){
  const c = getClient(order.clientId);
  const dev = getDevice(order.device);
  const ctx = {
    cliente: c.name.split(" ")[0], equipo: `${order.brand} ${order.model}`, num: order.num,
    presupuesto: fmtMoney(order.estimate), saldo: fmtMoney(orderBalance(order)),
  };
  // suggested template by status
  const suggested = templates.find(t => t.trigger===order.status) || templates[0];
  const [tplId, setTplId] = React.useState(suggested.id);
  const tpl = templates.find(t=>t.id===tplId) || suggested;
  const [channel, setChannel] = React.useState(tpl.channel);
  const [text, setText] = React.useState(fillTemplate(tpl.body, ctx));

  React.useEffect(()=>{ setText(fillTemplate(tpl.body, ctx)); setChannel(tpl.channel); }, [tplId]);

  function send(){
    onSend({ id:"n_"+Date.now(), orderNum:order.num, clientName:c.name, channel, template:tplId, t:new Date().toISOString(), status:"enviado", preview:text.slice(0,90)+(text.length>90?"…":"") });
  }

  return (
    <ModalShell title="Avisar al cliente" onClose={onClose} maxWidth={500}>
      <div style={{ padding:"20px 22px", display:"flex", flexDirection:"column", gap:15 }}>
        <div style={{ display:"flex", alignItems:"center", gap:11, padding:"11px 13px", borderRadius:10, background:"var(--surface-2)" }}>
          <Avatar name={c.name} hue={256} size={38} />
          <div style={{ flex:1, minWidth:0 }}>
            <div style={{ fontSize:14, fontWeight:700 }}>{c.name}</div>
            <div style={{ fontSize:12.5, color:"var(--muted)" }}><span className="mono">{c.phone}</span> · {c.email}</div>
          </div>
        </div>

        <Field label="Mensaje">
          <div style={{ position:"relative" }}>
            <select value={tplId} onChange={e=>setTplId(e.target.value)} style={{ ...inputStyle, appearance:"none", paddingRight:34, cursor:"pointer", marginBottom:10 }}>
              {templates.map(t=><option key={t.id} value={t.id}>{t.label}</option>)}
            </select>
            <Icon name="chevronDown" size={15} style={{ position:"absolute", right:12, top:18, transform:"translateY(-50%)", color:"var(--faint)", pointerEvents:"none" }} />
          </div>
          <textarea value={text} onChange={e=>setText(e.target.value)} rows={4} style={{ ...inputStyle, resize:"vertical", lineHeight:1.5 }} />
        </Field>

        <Field label="Enviar por">
          <div style={{ display:"flex", gap:8 }}>
            {[["email","Email","sms"],["whatsapp","WhatsApp","whatsapp"],["both","Ambos","bell"]].map(([id,l,ic])=>{
              const sel = channel===id;
              return (
                <button key={id} onClick={()=>setChannel(id)} style={{ flex:1, display:"inline-flex", alignItems:"center", justifyContent:"center", gap:7, padding:"10px", borderRadius:9, fontSize:13, fontWeight:600, cursor:"pointer",
                  border:`1px solid ${sel?"var(--accent)":"var(--line)"}`, background: sel?"var(--accent-soft)":"var(--surface)", color: sel?"var(--accent-ink)":"var(--ink-2)" }}>
                  <Icon name={ic} size={16} /> {l}
                </button>
              );
            })}
          </div>
        </Field>
      </div>
      <div style={{ display:"flex", justifyContent:"flex-end", gap:10, padding:"16px 22px", borderTop:"1px solid var(--line)" }}>
        <Btn variant="secondary" onClick={onClose}>Cancelar</Btn>
        <Btn icon="whatsapp" onClick={send}>Enviar mensaje</Btn>
      </div>
    </ModalShell>
  );
}

Object.assign(window, { Notificaciones, ChannelIcon, NotifyModal });
