/* journey.jsx — Orchestrateur de parcours métier (liste + builder vertical type BPMN) */
const { useState } = React;

const uid = () => Math.random().toString(36).slice(2, 9);

/* ---------- LISTE DES PARCOURS ---------- */
function JourneysView({ open, onSimulate }) {
  const D = window.DATA;
  return (
    <div className="page page--wide">
      <div className="page-head">
        <div className="page-head__txt">
          <h1>Parcours métier</h1>
          <p>Modélisez vos processus de confiance en orchestrant les briques de services. Chaque parcours enchaîne vérifications, formulaires, signatures et archivage.</p>
        </div>
        <div className="page-head__actions">
          <button className="btn btn--primary" onClick={() => open("new")}><Ic name="Plus" /> Nouveau parcours</button>
        </div>
      </div>

      <div className="grid cols-2">
        {D.JOURNEYS.map(j => (
          <div key={j.id} className="card jcard" style={{ padding:0, border:"1px solid var(--border)", display:"flex", flexDirection:"column" }}>
            <div style={{ padding:18, display:"flex", flexDirection:"column", gap:14, flex:1 }}>
              <div style={{ display:"flex", alignItems:"flex-start", gap:12 }}>
                <span className="svc-ic" style={{ background:"var(--surface-3)", color:"var(--text-2)" }}><Ic name="Flow" /></span>
                <div style={{ flex:1, minWidth:0 }}>
                  <div style={{ fontWeight:600, fontSize:15 }}>{j.name}</div>
                  <div className="muted" style={{ fontSize:12, marginTop:2 }}>{j.env} · {j.version} · maj {j.updated}</div>
                </div>
                <StatusBadge s={j.status} />
              </div>
              <p style={{ margin:0, fontSize:12.5, color:"var(--text-2)", lineHeight:1.5, display:"-webkit-box", WebkitLineClamp:2, WebkitBoxOrient:"vertical", overflow:"hidden" }}>{j.desc}</p>
              {/* mini chips of the chain */}
              <div style={{ display:"flex", gap:6, flexWrap:"wrap", alignItems:"center" }}>
                {j.steps.slice(0,6).map((s,i) => {
                  const svc = s.kind==="service" ? D.svc(s.serviceId) : null;
                  const tone = svc ? svc.tone : s.kind==="gate" ? "amber" : "gray";
                  return <React.Fragment key={i}>
                    {i>0 && <Ic name="ChevRight" width={12} height={12} style={{ color:"var(--text-3)" }} />}
                    <span className="svc-ic" style={{ width:26, height:26, borderRadius:7, background: toneSoft(tone), color: toneVar(tone) }}>
                      <Ic name={svc ? svc.icon : s.kind==="gate" ? "Branch" : "Form"} width={14} height={14} />
                    </span>
                  </React.Fragment>;
                })}
              </div>
            </div>
            <div style={{ display:"flex", borderTop:"1px solid var(--border)" }}>
              {[["Étapes", j.steps.length],["Exéc. / 30 j", fmt(j.runs30)],["Conversion", j.conv+" %"]].map(([l,v],i) => (
                <div key={i} style={{ flex:1, padding:"12px 16px", borderLeft: i?"1px solid var(--border)":"none" }}>
                  <div className="mono" style={{ fontSize:15, fontWeight:600 }}>{v}</div>
                  <div style={{ fontSize:11, color:"var(--text-3)" }}>{l}</div>
                </div>
              ))}
            </div>
            <div style={{ display:"flex", gap:8, padding:"12px 16px", borderTop:"1px solid var(--border)", background:"var(--surface-2)" }}>
              <button className="btn btn--sm" style={{ flex:1 }} onClick={() => open(j.id)}><Ic name="Edit" width={15} height={15}/> Ouvrir l'orchestrateur</button>
              <button className="btn btn--sm btn--primary" style={{ flex:1 }} onClick={() => onSimulate && onSimulate(j)}><Ic name="Eye" width={15} height={15}/> Simuler</button>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

/* ---------- BUILDER ---------- */
function emptyJourney() {
  return { id:uid(), name:"Nouveau parcours", status:"draft", version:"v1", env:"Bac à sable",
    desc:"", steps:[], owner:"Camille Roux", updated:"à l'instant", runs30:0, conv:0 };
}

function JourneyBuilder({ journey, onBack, onOpenForm, onSimulate }) {
  const D = window.DATA;
  const [steps, setSteps] = useState(() => journey.steps.map(s => ({ ...s, _id: uid() })));
  const [name, setName] = useState(journey.name);
  const [sel, setSel] = useState(null);
  const [picker, setPicker] = useState(null);   // index où insérer
  const [status, setStatus] = useState(journey.status);
  const [toast, setToast] = useState(null);

  const selStep = steps.find(s => s._id === sel);
  const subscribed = D.SERVICES.filter(s => s.subscribed);

  const flash = (m) => { setToast(m); setTimeout(() => setToast(null), 2200); };

  const insert = (item, at) => {
    const node = item.kind === "gate"
      ? { _id:uid(), kind:"gate", label:"Condition", sub:"Définir la règle de branchement" }
      : item.kind === "form"
      ? { _id:uid(), kind:"form", label:"Nouveau formulaire", sub:"0 champ", fields:[] }
      : { _id:uid(), kind:"service", serviceId:item.id, label:item.name, sub:item.code + " · " + item.cat, provider:(D.defProv(item)||{}).id };
    setSteps(s => { const c=[...s]; c.splice(at, 0, node); return c; });
    setSel(node._id); setPicker(null);
  };
  const remove = (id) => { setSteps(s => s.filter(x => x._id!==id)); if (sel===id) setSel(null); };
  const move = (id, dir) => setSteps(s => {
    const i = s.findIndex(x => x._id===id); const j = i+dir;
    if (j<0 || j>=s.length) return s;
    const c=[...s]; [c[i],c[j]]=[c[j],c[i]]; return c;
  });
  const patch = (id, p) => setSteps(s => s.map(x => x._id===id ? {...x, ...p} : x));

  return (
    <div className="page page--wide">
      {/* header */}
      <div style={{ display:"flex", alignItems:"center", gap:14, marginBottom:18, flexWrap:"wrap" }}>
        <button className="btn btn--ghost btn--sm btn--icon" onClick={onBack}><Ic name="ChevRight" style={{ transform:"rotate(180deg)" }} /></button>
        <div style={{ flex:1, minWidth:200 }}>
          <input value={name} onChange={e=>setName(e.target.value)} className="builder-title"
            style={{ border:"none", background:"none", fontSize:21, fontWeight:600, letterSpacing:"-0.02em", width:"100%", padding:"2px 4px", borderRadius:6, color:"var(--text)" }} />
          <div style={{ display:"flex", gap:8, alignItems:"center", marginTop:4, paddingLeft:4 }}>
            <StatusBadge s={status} />
            <span className="muted" style={{ fontSize:12 }}>{journey.env} · {journey.version} · {steps.length} étapes</span>
          </div>
        </div>
        <button className="btn" onClick={() => onSimulate && onSimulate({ ...journey, name, steps })}><Ic name="Eye" /> Simuler</button>
        {status==="draft"
          ? <button className="btn btn--primary" onClick={() => { setStatus("published"); flash("Parcours publié en production"); }}><Ic name="Bolt" /> Publier</button>
          : <button className="btn" onClick={() => { setStatus("draft"); flash("Parcours repassé en brouillon"); }}><Ic name="Pause" /> Dépublier</button>}
      </div>

      <div className="flowwrap">
        {/* FLOW */}
        <div className="card" style={{ padding:"22px 18px", background:"var(--surface-2)" }}>
          <div className="flow">
            <div className="flow-cap flow-cap--start"><Ic name="Play" width={15} height={15} /> Déclenchement du parcours</div>
            <div className="flow-link" />
            <button className="flow-add" title="Ajouter une étape" onClick={() => setPicker(0)}><Ic name="Plus" /></button>

            {steps.length===0 && (
              <div className="empty" style={{ padding:"28px 20px" }}>
                <Ic name="Layers" /><div>Aucune étape. Ajoutez une brique de confiance<br/>depuis la palette pour démarrer l'orchestration.</div>
              </div>
            )}

            {steps.map((s, i) => {
              const svc = s.kind==="service" ? D.svc(s.serviceId) : null;
              return (
                <React.Fragment key={s._id}>
                  <div className="flow-link" />
                  {s.kind==="gate" ? (
                    <div className={"flow-gate" + (sel===s._id?" is-selected":"")} onClick={() => setSel(s._id)} style={ sel===s._id?{boxShadow:"0 0 0 3px var(--primary-ring)", borderColor:"var(--primary)"}:{} }>
                      <span className="gw"><Ic name="Branch" /></span>
                      <div style={{ flex:1 }}>
                        <div style={{ fontWeight:600, fontSize:13.5 }}>{s.label}</div>
                        <div style={{ fontSize:12, color:"oklch(0.5 0.1 60)" }}>{s.sub}</div>
                      </div>
                      <NodeActs i={i} n={steps.length} onUp={()=>move(s._id,-1)} onDown={()=>move(s._id,1)} onDel={()=>remove(s._id)} />
                    </div>
                  ) : (
                    <div className={"flow-node" + (sel===s._id?" is-selected":"")} onClick={() => setSel(s._id)}>
                      <span className="flow-node__grip"><Ic name="Grip" width={16} height={16} /></span>
                      <span className="svc-ic" style={{ width:36, height:36, background: svc?toneSoft(svc.tone):"var(--surface-3)", color: svc?toneVar(svc.tone):"var(--text-2)" }}>
                        <Ic name={svc ? svc.icon : "Form"} width={18} height={18} />
                      </span>
                      <div className="flow-node__txt">
                        <div className="flow-node__name">{s.label}</div>
                        <div className="flow-node__sub">{s.kind==="form" ? `${(s.fields||[]).length} champ(s) · formulaire` : s.sub}</div>
                      </div>
                      {svc && (() => {
                        const prov = D.provOf(svc, s.provider) || D.defProv(svc);
                        return prov ? <span className="prov-pill" title={"Fournisseur : " + prov.name}><ProviderTile p={prov} size={19} /><span>{prov.name}</span></span> : null;
                      })()}
                      {s.kind==="form" && <button className="btn btn--sm" onClick={(e)=>{e.stopPropagation(); onOpenForm(s, (fields)=>patch(s._id,{fields}));}}><Ic name="Edit" width={14} height={14}/> Éditer</button>}
                      <NodeActs i={i} n={steps.length} onUp={()=>move(s._id,-1)} onDown={()=>move(s._id,1)} onDel={()=>remove(s._id)} />
                    </div>
                  )}
                  <div className="flow-link" />
                  <button className="flow-add" onClick={() => setPicker(i+1)}><Ic name="Plus" /></button>
                </React.Fragment>
              );
            })}

            <div className="flow-link" />
            <div className="flow-cap flow-cap--end"><Ic name="Check" width={15} height={15} /> Fin du parcours</div>
          </div>
        </div>

        {/* RIGHT COLUMN */}
        <div style={{ position:"sticky", top:76, display:"flex", flexDirection:"column", gap:"var(--gap)" }}>
          {selStep ? (
            <NodeConfig step={selStep} svc={selStep.serviceId?D.svc(selStep.serviceId):null}
              onChange={(p)=>patch(selStep._id,p)} onClose={()=>setSel(null)}
              onOpenForm={selStep.kind==="form" ? ()=>onOpenForm(selStep,(fields)=>patch(selStep._id,{fields})) : null} />
          ) : (
            <div className="card">
              <div className="card__head"><div><h3>Palette de services</h3><p>Cliquez pour ajouter à la fin</p></div></div>
              <div className="card__body" style={{ display:"flex", flexDirection:"column", gap:8 }}>
                {subscribed.map(s => (
                  <button key={s.id} className="palette-item" onClick={()=>insert(s, steps.length)}>
                    <SvcIcon service={s} size={32} />
                    <div style={{ flex:1, minWidth:0 }}><div style={{ fontSize:12.5, fontWeight:600 }}>{s.name}</div><div style={{ fontSize:11, color:"var(--text-3)" }}>{s.code}</div></div>
                    <Ic name="Plus" width={15} height={15} style={{ color:"var(--text-3)" }} />
                  </button>
                ))}
                <hr className="divider" style={{ margin:"4px 0" }} />
                <button className="palette-item" onClick={()=>insert({kind:"form"}, steps.length)}>
                  <span className="svc-ic" style={{ width:32, height:32, background:"var(--surface-3)", color:"var(--text-2)" }}><Ic name="Form" width={16} height={16}/></span>
                  <div style={{ flex:1 }}><div style={{ fontSize:12.5, fontWeight:600 }}>Formulaire</div><div style={{ fontSize:11, color:"var(--text-3)" }}>Saisie client</div></div>
                  <Ic name="Plus" width={15} height={15} style={{ color:"var(--text-3)" }} />
                </button>
                <button className="palette-item" onClick={()=>insert({kind:"gate"}, steps.length)}>
                  <span className="svc-ic" style={{ width:32, height:32, background:"var(--amber-soft)", color:"var(--amber)" }}><Ic name="Branch" width={16} height={16}/></span>
                  <div style={{ flex:1 }}><div style={{ fontSize:12.5, fontWeight:600 }}>Condition (branchement)</div><div style={{ fontSize:11, color:"var(--text-3)" }}>Passerelle BPMN</div></div>
                  <Ic name="Plus" width={15} height={15} style={{ color:"var(--text-3)" }} />
                </button>
              </div>
              <div className="card__foot"><Ic name="Info" width={15} height={15}/><span className="muted" style={{ fontSize:11.5 }}>Sélectionnez une étape pour la configurer.</span></div>
            </div>
          )}
        </div>
      </div>

      {/* PICKER MODAL */}
      {picker !== null && (
        <Modal title="Ajouter une étape" icon="Plus" onClose={()=>setPicker(null)}>
          <div style={{ fontSize:12.5, color:"var(--text-3)", marginBottom:12 }}>Briques de confiance souscrites</div>
          <div className="grid cols-2" style={{ gap:9 }}>
            {subscribed.map(s => (
              <button key={s.id} className="palette-item" onClick={()=>insert(s, picker)}>
                <SvcIcon service={s} size={32} />
                <div style={{ flex:1, minWidth:0 }}><div style={{ fontSize:12.5, fontWeight:600 }}>{s.name}</div><div style={{ fontSize:11, color:"var(--text-3)" }}>{eur(s.price)} / {s.unit}</div></div>
              </button>
            ))}
          </div>
          <div style={{ fontSize:12.5, color:"var(--text-3)", margin:"16px 0 12px" }}>Logique de parcours</div>
          <div className="grid cols-2" style={{ gap:9 }}>
            <button className="palette-item" onClick={()=>insert({kind:"form"}, picker)}>
              <span className="svc-ic" style={{ width:32, height:32, background:"var(--surface-3)", color:"var(--text-2)" }}><Ic name="Form" width={16} height={16}/></span>
              <div style={{ flex:1 }}><div style={{ fontSize:12.5, fontWeight:600 }}>Formulaire</div></div>
            </button>
            <button className="palette-item" onClick={()=>insert({kind:"gate"}, picker)}>
              <span className="svc-ic" style={{ width:32, height:32, background:"var(--amber-soft)", color:"var(--amber)" }}><Ic name="Branch" width={16} height={16}/></span>
              <div style={{ flex:1 }}><div style={{ fontSize:12.5, fontWeight:600 }}>Condition</div></div>
            </button>
          </div>
        </Modal>
      )}

      {toast && <div style={{ position:"fixed", bottom:24, left:"50%", transform:"translateX(-50%)", background:"var(--text)", color:"#fff", padding:"11px 18px", borderRadius:10, fontSize:13, fontWeight:500, boxShadow:"var(--shadow-lg)", zIndex:200, display:"flex", gap:9, alignItems:"center", animation:"pop .18s ease" }}><Ic name="Check" width={16} height={16}/> {toast}</div>}
    </div>
  );
}

function NodeActs({ i, n, onUp, onDown, onDel }) {
  return (
    <div className="flow-node__acts" onClick={e=>e.stopPropagation()}>
      <button className="btn btn--ghost btn--icon btn--sm" disabled={i===0} onClick={onUp} title="Monter" style={{opacity:i===0?.35:1}}><Ic name="ArrowUp" width={14} height={14}/></button>
      <button className="btn btn--ghost btn--icon btn--sm" disabled={i===n-1} onClick={onDown} title="Descendre" style={{opacity:i===n-1?.35:1}}><Ic name="ArrowDown" width={14} height={14}/></button>
      <button className="btn btn--ghost btn--icon btn--sm btn--danger" onClick={onDel} title="Supprimer"><Ic name="Trash" width={14} height={14}/></button>
    </div>
  );
}

function NodeConfig({ step, svc, onChange, onClose, onOpenForm }) {
  return (
    <div className="card" style={{ animation:"slidein .16s ease" }}>
      <div className="card__head">
        <span className="svc-ic" style={{ width:32, height:32, background: svc?toneSoft(svc.tone):step.kind==="gate"?"var(--amber-soft)":"var(--surface-3)", color: svc?toneVar(svc.tone):step.kind==="gate"?"var(--amber)":"var(--text-2)" }}>
          <Ic name={svc?svc.icon:step.kind==="gate"?"Branch":"Form"} width={16} height={16}/>
        </span>
        <div style={{ flex:1 }}><h3 style={{ fontSize:13.5 }}>Configuration</h3><p>{svc?svc.code:step.kind==="gate"?"Branchement":"Formulaire"}</p></div>
        <button className="btn btn--ghost btn--icon btn--sm" onClick={onClose}><Ic name="X" /></button>
      </div>
      <div className="card__body">
        <div className="field"><label>Libellé de l'étape</label><input className="input" value={step.label} onChange={e=>onChange({label:e.target.value})} /></div>

        {svc && <>
          <div className="field"><label>Fournisseur (connecteur)</label>
            <select className="select" value={step.provider || (window.DATA.defProv(svc)||{}).id || ""} onChange={e=>onChange({provider:e.target.value})}>
              {svc.providers.filter(p=>p.status==="connected").map(p =>
                <option key={p.id} value={p.id}>{p.name}{p.kind==="native"?" (natif)":""}{svc.defaultProvider===p.id?" — défaut":""}</option>)}
            </select>
            <span className="hint">{(() => { const p = window.DATA.provOf(svc, step.provider) || window.DATA.defProv(svc); return p ? `${p.kind==="native"?"Brique native Doxallia":"Connecteur externe certifié"} · ${p.certif.join(", ")}` : ""; })()}</span>
          </div>
          <div className="field"><label>Niveau de garantie</label>
            <select className="select" defaultValue="substantiel"><option value="faible">Faible</option><option value="substantiel">Substantiel</option><option value="eleve">Élevé</option></select>
          </div>
          <div className="field" style={{marginBottom:0}}><label>Action en cas d'échec</label>
            <select className="select"><option>Revue manuelle conseiller</option><option>Arrêt du parcours</option><option>Nouvelle tentative</option></select>
          </div>
          <hr className="divider" style={{ margin:"16px 0" }} />
          <div style={{ display:"flex", justifyContent:"space-between", fontSize:12.5 }}><span className="muted">Coût unitaire</span><span className="mono" style={{ fontWeight:600 }}>{eur(svc.price)} / {svc.unit}</span></div>
        </>}

        {step.kind==="gate" && <>
          <div className="field"><label>Variable évaluée</label>
            <select className="select"><option>Score de risque KYC</option><option>Résultat vérification PVID</option><option>Montant du contrat</option></select>
          </div>
          <div className="field"><label>Condition</label>
            <div style={{ display:"flex", gap:8 }}>
              <select className="select" style={{ flex:1 }}><option>est supérieur à</option><option>est inférieur à</option><option>est égal à</option></select>
              <input className="input mono" defaultValue="70" style={{ width:80 }} />
            </div>
          </div>
          <div className="field" style={{marginBottom:0}}><label>Sinon</label><input className="input" value={step.sub} onChange={e=>onChange({sub:e.target.value})} /></div>
        </>}

        {step.kind==="form" && <>
          <p className="muted" style={{ fontSize:12.5, marginTop:0 }}>Ce formulaire comporte <b>{(step.fields||[]).length} champ(s)</b>. Ouvrez le constructeur pour les modifier.</p>
          <button className="btn btn--primary" style={{ width:"100%" }} onClick={onOpenForm}><Ic name="Form" /> Ouvrir le constructeur de formulaire</button>
        </>}
      </div>
    </div>
  );
}

Object.assign(window, { JourneysView, JourneyBuilder, emptyJourney });
