/* educator-extras.jsx — Contacts, TrainerKPIs, Mailing */

/* ── CONTACTS ── */
const CRM_ACCOUNTS = [
  { id:1, company:"Accenture NL",       type:"Enterprise",  learners:84, country:"Netherlands", contact:"Sandra Visser",  email:"s.visser@accenture.com",  status:"active"   },
  { id:2, company:"ING Bank",            type:"Financial",   learners:42, country:"Netherlands", contact:"Pieter Smit",    email:"p.smit@ing.nl",           status:"active"   },
  { id:3, company:"Shell",               type:"Energy",      learners:31, country:"Netherlands", contact:"Tom van Berg",   email:"t.vanberg@shell.com",      status:"active"   },
  { id:4, company:"KPMG Advisory",       type:"Consulting",  learners:28, country:"Netherlands", contact:"Lisa Janssen",   email:"l.janssen@kpmg.nl",       status:"active"   },
  { id:5, company:"Philips Healthcare",  type:"Technology",  learners:19, country:"Netherlands", contact:"Marc Brouwer",   email:"m.brouwer@philips.com",    status:"inactive" },
  { id:6, company:"Rijkswaterstaat",     type:"Government",  learners:56, country:"Netherlands", contact:"Anna de Boer",   email:"a.deboer@rws.nl",          status:"active"   },
  { id:7, company:"Deloitte NL",         type:"Consulting",  learners:33, country:"Netherlands", contact:"Sophie Müller",  email:"s.muller@deloitte.com",    status:"active"   },
];

const TYPE_COLORS = {
  Enterprise:{ bg:"#eef5fc", color:"#1281c4" },
  Financial: { bg:"#e8f5e9", color:"#2e7d32" },
  Energy:    { bg:"#fff3e0", color:"#e65100" },
  Consulting:{ bg:"#f3e8ff", color:"#7c3aed" },
  Technology:{ bg:"#e0f7fa", color:"#007a85" },
  Government:{ bg:"#fff8e1", color:"#f57f17" },
};

function Contacts() {
  const [search, setSearch] = useState("");
  const [selected, setSelected] = useState(null);
  const filtered = CRM_ACCOUNTS.filter(a => !search || a.company.toLowerCase().includes(search.toLowerCase()) || a.contact.toLowerCase().includes(search.toLowerCase()));
  return (
    <div>
      <div className="between" style={{ marginBottom:22 }}>
        <div className="page-head" style={{ marginBottom:0 }}>
          <h1>Contacts</h1>
          <p>CRM accounts and key contacts for training organisations.</p>
        </div>
        <button className="btn btn-acc" disabled title="Binnenkort" style={{ opacity:.5, cursor:"not-allowed" }}><Icon name="plus" size={16}/>New account</button>
      </div>
      <div className="stat-grid" style={{ marginBottom:20 }}>
        {[
          { label:"Total accounts", val:CRM_ACCOUNTS.length,                            icon:"users",  bg:"var(--vh-blue-50)", ic:"var(--blue)" },
          { label:"Active",         val:CRM_ACCOUNTS.filter(a=>a.status==="active").length, icon:"check",  bg:"#e8f5e9",       ic:"#2e7d32"    },
          { label:"Total learners", val:CRM_ACCOUNTS.reduce((s,a)=>s+a.learners,0),     icon:"graduation", bg:"#fff3e0",      ic:"#e65100"    },
          { label:"Countries",      val:[...new Set(CRM_ACCOUNTS.map(a=>a.country))].length, icon:"globe", bg:"#f3e8ff",      ic:"#7c3aed"    },
        ].map(s=>(
          <div key={s.label} className="card stat-card">
            <div className="between" style={{ marginBottom:12 }}>
              <div className="eyebrow">{s.label}</div>
              <div className="stat-ico" style={{ background:s.bg }}><Icon name={s.icon} size={17} style={{ color:s.ic }}/></div>
            </div>
            <div className="kpi" style={{ fontSize:30 }}>{s.val}</div>
          </div>
        ))}
      </div>
      <div className="card" style={{ padding:0, overflow:"hidden" }}>
        <div style={{ padding:"14px 20px", borderBottom:"1px solid var(--line)", display:"flex", gap:12, alignItems:"center" }}>
          <label className="search" style={{ flex:1, maxWidth:320 }}>
            <Icon name="search" size={16}/>
            <input placeholder="Search accounts or contacts…" value={search} onChange={e=>setSearch(e.target.value)}/>
          </label>
        </div>
        <table className="tbl">
          <thead><tr><th>Organisation</th><th>Type</th><th>Key contact</th><th>Learners</th><th>Status</th><th></th></tr></thead>
          <tbody>
            {filtered.map(a=>{
              const tc = TYPE_COLORS[a.type]||{bg:"#f5f5f5",color:"#616161"};
              return (
                <tr key={a.id} onClick={()=>setSelected(a)} style={{ cursor:"pointer" }}>
                  <td><div style={{ fontWeight:700, fontSize:14, color:"var(--ink)" }}>{a.company}</div><div style={{ fontSize:12, color:"var(--ink3)" }}>{a.country}</div></td>
                  <td><span style={{ fontSize:11.5, fontWeight:700, padding:"2px 8px", borderRadius:999, background:tc.bg, color:tc.color }}>{a.type}</span></td>
                  <td><div style={{ fontSize:13.5, fontWeight:600 }}>{a.contact}</div><div style={{ fontSize:12, color:"var(--ink3)" }}>{a.email}</div></td>
                  <td><div style={{ fontFamily:"var(--display)", fontWeight:700, fontSize:16 }}>{a.learners}</div></td>
                  <td><span style={{ fontSize:11.5, fontWeight:700, padding:"2px 8px", borderRadius:999, background:a.status==="active"?"#e8f5e9":"#f5f5f5", color:a.status==="active"?"#2e7d32":"#616161" }}>{a.status}</span></td>
                  <td><button className="btn btn-ghost btn-sm">View</button></td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}

/* ── TRAINER KPIS ── */
const TRAINER_KPI_DATA = [
  { name:"Jonas Bakker",  ti:"JB", bg:"#1281c4", sessions:12, learners:142, avgRating:4.7, completion:88, nps:72, courses:["IPMA-D","IPMA-C","Scrum"]          },
  { name:"Eva Groot",     ti:"EG", bg:"#f99d25", sessions:9,  learners:98,  avgRating:4.8, completion:92, nps:81, courses:["PRINCE2 F","PRINCE2 P"]             },
  { name:"Pieter van Dam",ti:"PD", bg:"#3bc1ce", sessions:7,  learners:64,  avgRating:4.5, completion:79, nps:65, courses:["BiSL","ASL"]                        },
  { name:"Maria Santos",  ti:"MS", bg:"#7c3aed", sessions:11, learners:118, avgRating:4.6, completion:85, nps:70, courses:["ITIL 4","ISO 27001"]                 },
];

function StarRating({ val }) {
  return (
    <div style={{ display:"flex", alignItems:"center", gap:3 }}>
      {[1,2,3,4,5].map(s=>(
        <svg key={s} width="13" height="13" viewBox="0 0 24 24" fill={val>=s?"#f99d25":"#e0e0e0"} stroke="none"><path d="M12 3l2.9 5.9 6.5.9-4.7 4.6 1.1 6.5L12 18l-5.8 3 1.1-6.5-4.7-4.6 6.5-.9z"/></svg>
      ))}
      <span style={{ fontSize:13, fontWeight:700, color:"var(--ink2)", marginLeft:4 }}>{val.toFixed(1)}</span>
    </div>
  );
}

function TrainerKPIs() {
  return (
    <div>
      <div className="between" style={{ marginBottom:22 }}>
        <div className="page-head" style={{ marginBottom:0 }}>
          <h1>Trainer KPIs</h1>
          <p>Performance metrics for all active trainers this quarter.</p>
        </div>
        <span className="tag blue"><Icon name="calendar" size={13}/>Q2 2026</span>
      </div>
      <div className="stat-grid" style={{ marginBottom:24 }}>
        {[
          { label:"Active trainers",   val:TRAINER_KPI_DATA.length,                                                          icon:"graduation", bg:"var(--vh-blue-50)", ic:"var(--blue)" },
          { label:"Total sessions",    val:TRAINER_KPI_DATA.reduce((s,t)=>s+t.sessions,0),                                   icon:"slides",     bg:"#e8f5e9",          ic:"#2e7d32"     },
          { label:"Total learners",    val:TRAINER_KPI_DATA.reduce((s,t)=>s+t.learners,0),                                   icon:"users",      bg:"#fff3e0",          ic:"#e65100"     },
          { label:"Avg rating",        val:(TRAINER_KPI_DATA.reduce((s,t)=>s+t.avgRating,0)/TRAINER_KPI_DATA.length).toFixed(1)+"★", icon:"star", bg:"#fff8e1",     ic:"#f57f17"     },
        ].map(s=>(
          <div key={s.label} className="card stat-card">
            <div className="between" style={{ marginBottom:12 }}>
              <div className="eyebrow">{s.label}</div>
              <div className="stat-ico" style={{ background:s.bg }}><Icon name={s.icon} size={17} style={{ color:s.ic }}/></div>
            </div>
            <div className="kpi" style={{ fontSize:30 }}>{s.val}</div>
          </div>
        ))}
      </div>
      <div style={{ display:"flex", flexDirection:"column", gap:14 }}>
        {TRAINER_KPI_DATA.map(t=>{
          const npsColor = t.nps>=75?"#2e7d32":t.nps>=50?"#e65100":"#c62828";
          return (
            <div key={t.name} className="card" style={{ padding:0, overflow:"hidden" }}>
              <div style={{ display:"grid", gridTemplateColumns:"260px 1fr", alignItems:"stretch" }}>
                {/* Left: trainer info */}
                <div style={{ padding:"20px 24px", borderRight:"1px solid var(--line)", display:"flex", flexDirection:"column", gap:10 }}>
                  <div style={{ display:"flex", alignItems:"center", gap:13 }}>
                    <div style={{ width:48, height:48, borderRadius:13, background:t.bg, display:"grid", placeItems:"center", color:"#fff", fontFamily:"var(--display)", fontWeight:800, fontSize:18 }}>{t.ti}</div>
                    <div>
                      <div style={{ fontWeight:700, fontSize:15.5, color:"var(--ink)" }}>{t.name}</div>
                      <div style={{ fontSize:12, color:"var(--ink3)", marginTop:2 }}>{t.courses.join(" · ")}</div>
                    </div>
                  </div>
                  <StarRating val={t.avgRating}/>
                  <div style={{ fontSize:12.5, color:"var(--ink3)" }}>{t.sessions} sessions · {t.learners} learners</div>
                </div>
                {/* Right: KPI metrics */}
                <div style={{ padding:"20px 24px", display:"grid", gridTemplateColumns:"repeat(3,1fr)", gap:20, alignItems:"center" }}>
                  <div>
                    <div className="eyebrow" style={{ marginBottom:8 }}>Completion rate</div>
                    <div style={{ display:"flex", alignItems:"center", gap:10 }}>
                      <Ring value={t.completion} size={52} stroke={6} color={t.completion>=85?"#2e7d32":t.completion>=70?"#f99d25":"#c62828"}>
                        <span style={{ fontFamily:"var(--display)", fontWeight:800, fontSize:13 }}>{t.completion}%</span>
                      </Ring>
                    </div>
                  </div>
                  <div>
                    <div className="eyebrow" style={{ marginBottom:8 }}>NPS score</div>
                    <div style={{ fontFamily:"var(--display)", fontWeight:800, fontSize:32, color:npsColor }}>{t.nps}</div>
                    <div style={{ fontSize:12, color:"var(--ink3)", marginTop:2 }}>{t.nps>=75?"Excellent":t.nps>=50?"Good":"Needs attention"}</div>
                  </div>
                  <div>
                    <div className="eyebrow" style={{ marginBottom:10 }}>Sessions trend</div>
                    <div style={{ display:"flex", alignItems:"flex-end", gap:4, height:36 }}>
                      {[40,55,70,65,80,90,t.completion].map((v,i)=>(
                        <div key={i} style={{ flex:1, background:i===6?"var(--blue)":"var(--surface-3)", borderRadius:3, height:v*36/100+"px" }}/>
                      ))}
                    </div>
                  </div>
                </div>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

/* ── MAILING ── */
const CAMPAIGNS = [
  { id:1, name:"IPMA June 2026 — Registration reminder", status:"sent",      sent:142, opened:98,  clicked:34, date:"28 May 2026", list:"IPMA Cohort Q2" },
  { id:2, name:"New course: BiSL Next Foundation",        status:"sent",      sent:380, opened:211, clicked:67, date:"15 May 2026", list:"All learners"   },
  { id:3, name:"PRINCE2 Amsterdam — Last seats!",          status:"scheduled", sent:0,   opened:0,   clicked:0,  date:"5 Jun 2026",  list:"PRINCE2 interest" },
  { id:4, name:"Q3 2026 Training calendar",                status:"draft",     sent:0,   opened:0,   clicked:0,  date:"—",           list:"All learners"   },
  { id:5, name:"Certificate — IPMA-D May cohort",          status:"sent",      sent:24,  opened:23,  clicked:18, date:"10 May 2026", list:"May cohort"     },
];

const CAMP_STATUS = {
  sent:      { label:"Sent",      bg:"#e8f5e9", color:"#2e7d32" },
  scheduled: { label:"Scheduled", bg:"#e3f2fd", color:"#1565c0" },
  draft:     { label:"Draft",     bg:"#f5f5f5", color:"#616161" },
};

function Mailing() {
  const [showNew, setShowNew] = useState(false);
  const totalSent = CAMPAIGNS.reduce((s,c)=>s+c.sent,0);
  const totalOpened = CAMPAIGNS.reduce((s,c)=>s+c.opened,0);
  const totalClicked = CAMPAIGNS.reduce((s,c)=>s+c.clicked,0);
  return (
    <div>
      <div className="between" style={{ marginBottom:22 }}>
        <div className="page-head" style={{ marginBottom:0 }}>
          <h1>Mailing</h1>
          <p>Email campaigns for learners, cohorts and training announcements.</p>
        </div>
        <button className="btn btn-acc" onClick={()=>setShowNew(true)}><Icon name="plus" size={16}/>New campaign</button>
      </div>
      <div className="stat-grid" style={{ marginBottom:22 }}>
        {[
          { label:"Total sent",    val:totalSent.toLocaleString(),                                      icon:"mail",     bg:"var(--vh-blue-50)", ic:"var(--blue)" },
          { label:"Open rate",     val:totalSent?Math.round((totalOpened/totalSent)*100)+"%":"—",       icon:"checkCircle", bg:"#e8f5e9",         ic:"#2e7d32"     },
          { label:"Click rate",    val:totalSent?Math.round((totalClicked/totalSent)*100)+"%":"—",       icon:"arrowR",   bg:"#fff3e0",          ic:"#e65100"     },
          { label:"Campaigns",     val:CAMPAIGNS.length,                                                 icon:"list",     bg:"#f3e8ff",          ic:"#7c3aed"     },
        ].map(s=>(
          <div key={s.label} className="card stat-card">
            <div className="between" style={{ marginBottom:12 }}>
              <div className="eyebrow">{s.label}</div>
              <div className="stat-ico" style={{ background:s.bg }}><Icon name={s.icon} size={17} style={{ color:s.ic }}/></div>
            </div>
            <div className="kpi" style={{ fontSize:30 }}>{s.val}</div>
          </div>
        ))}
      </div>
      <div className="card" style={{ padding:0, overflow:"hidden" }}>
        <table className="tbl">
          <thead><tr><th>Campaign</th><th>List</th><th>Date</th><th>Sent</th><th>Opened</th><th>Clicked</th><th>Status</th><th></th></tr></thead>
          <tbody>
            {CAMPAIGNS.map(c=>{
              const st = CAMP_STATUS[c.status]||CAMP_STATUS.draft;
              const openRate = c.sent ? Math.round((c.opened/c.sent)*100)+"%" : "—";
              const clickRate = c.sent ? Math.round((c.clicked/c.sent)*100)+"%" : "—";
              return (
                <tr key={c.id}>
                  <td style={{ maxWidth:280 }}><div style={{ fontWeight:700, fontSize:13.5, color:"var(--ink)" }}>{c.name}</div></td>
                  <td><span style={{ fontSize:12, color:"var(--ink3)" }}>{c.list}</span></td>
                  <td><span style={{ fontSize:13, color:"var(--ink2)" }}>{c.date}</span></td>
                  <td><span style={{ fontFamily:"var(--display)", fontWeight:700 }}>{c.sent||"—"}</span></td>
                  <td><span style={{ fontFamily:"var(--display)", fontWeight:700, color:c.sent?"#2e7d32":"var(--ink3)" }}>{openRate}</span></td>
                  <td><span style={{ fontFamily:"var(--display)", fontWeight:700, color:c.sent?"#1281c4":"var(--ink3)" }}>{clickRate}</span></td>
                  <td><span style={{ fontSize:11.5, fontWeight:700, padding:"2px 8px", borderRadius:999, background:st.bg, color:st.color }}>{st.label}</span></td>
                  <td>
                    <div style={{ display:"flex", gap:6 }}>
                      <button className="btn btn-ghost btn-sm" disabled title="Binnenkort" style={{ opacity:.5, cursor:"not-allowed" }}>{c.status==="draft"?"Edit":"View"}</button>
                      {c.status==="draft"&&<button className="btn btn-pri btn-sm" disabled title="Binnenkort" style={{ opacity:.5, cursor:"not-allowed" }}>Send</button>}
                    </div>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>

      {showNew && (
        <div style={{ position:"fixed", inset:0, background:"rgba(13,26,52,.5)", backdropFilter:"blur(3px)", zIndex:200, display:"grid", placeItems:"center", padding:24 }}
          onClick={e=>{ if(e.target===e.currentTarget) setShowNew(false); }}>
          <div className="card" style={{ width:"100%", maxWidth:500, padding:28 }}>
            <div className="between" style={{ marginBottom:20 }}>
              <h2 style={{ fontSize:20, fontWeight:800 }}>New campaign</h2>
              <button onClick={()=>setShowNew(false)} style={{ width:30, height:30, borderRadius:8, background:"var(--surface-2)", border:"none", cursor:"pointer", display:"grid", placeItems:"center" }}><Icon name="x" size={15} style={{ color:"var(--ink3)" }}/></button>
            </div>
            <div style={{ display:"flex", flexDirection:"column", gap:13 }}>
              <div><label style={{ fontSize:12.5, fontWeight:700, color:"var(--ink2)", display:"block", marginBottom:5 }}>Subject line</label><input style={{ width:"100%", padding:"10px 12px", borderRadius:9, border:"1.5px solid var(--line)", outline:"none", fontSize:14, fontFamily:"var(--body)" }} placeholder="e.g. IPMA June 2026 — Registration now open"/></div>
              <div><label style={{ fontSize:12.5, fontWeight:700, color:"var(--ink2)", display:"block", marginBottom:5 }}>Recipient list</label><select style={{ width:"100%", padding:"10px 12px", borderRadius:9, border:"1.5px solid var(--line)", outline:"none", fontSize:14, fontFamily:"var(--body)", background:"#fff" }}><option>All learners</option><option>IPMA Cohort Q2</option><option>PRINCE2 interest</option><option>May cohort</option></select></div>
              <div><label style={{ fontSize:12.5, fontWeight:700, color:"var(--ink2)", display:"block", marginBottom:5 }}>Send date</label><input type="date" style={{ width:"100%", padding:"10px 12px", borderRadius:9, border:"1.5px solid var(--line)", outline:"none", fontSize:14, fontFamily:"var(--body)" }} defaultValue="2026-06-10"/></div>
              <div><label style={{ fontSize:12.5, fontWeight:700, color:"var(--ink2)", display:"block", marginBottom:5 }}>Message preview</label><textarea rows={4} style={{ width:"100%", padding:"10px 12px", borderRadius:9, border:"1.5px solid var(--line)", outline:"none", fontSize:14, fontFamily:"var(--body)", resize:"vertical" }} placeholder="Write your email message here…"/></div>
              <div style={{ display:"flex", gap:10, marginTop:4 }}>
                <button className="btn btn-pri" style={{ flex:1, padding:"12px", borderRadius:11 }} onClick={()=>setShowNew(false)}><Icon name="mail" size={16}/>Schedule campaign</button>
                <button className="btn btn-ghost" style={{ flex:1, padding:"12px", borderRadius:11 }} onClick={()=>setShowNew(false)}>Save as draft</button>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { Contacts, TrainerKPIs, Mailing });
