// MSP profile page: /directory/[slug]
// Long-tail SEO target. Full verification proof + services + journey timeline.

const { useState: useStateP } = React;

function ProfileView({ slug, onBack }) {
  const msp = window.MSPS.find(m => m.slug === slug);
  const [contactOpen, setContactOpen] = useStateP(false);
  if (!msp) return <div style={{padding:40}}>MSP not found</div>;
  const isTrusted = msp.stage === "trusted";

  return (
    <div>
      {contactOpen && <ContactModal msp={msp} onClose={()=>setContactOpen(false)}/>}
      {/* Breadcrumb */}
      <div style={{maxWidth:1320, margin:"0 auto", padding:"20px 32px 0", fontSize:13, color:"#6B7793"}}>
        <a href="#/" onClick={e=>{e.preventDefault(); onBack();}} style={{color:"#6B7793", textDecoration:"none"}}>Directory</a>
        <span style={{margin:"0 8px"}}>/</span>
        <span style={{color:"#071e47"}}>{msp.name}</span>
      </div>

      {/* Header section */}
      <section style={{
        position:"relative", overflow:"hidden",
        background:`linear-gradient(180deg, #EDF2F8 0%, #F4F7FB 100%)`,
        borderBottom:"1px solid #E4E9F2",
        marginTop:12,
      }}>
        <HexPattern opacity={0.05}/>
        <div style={{maxWidth:1320, margin:"0 auto", padding:"40px 32px 48px", display:"grid", gridTemplateColumns:"1fr 280px", gap:48, alignItems:"center", position:"relative"}}>
          <div>
            <div style={{display:"flex", gap:16, alignItems:"center", marginBottom:20}}>
              <MspMark msp={msp} size={64} rounded={16}/>
              <div>
                <div style={{display:"flex", alignItems:"center", gap:8, flexWrap:"wrap"}}>
                  <StageChip stage={msp.stage}/>
                  {msp.founding50 && <FoundingBadge/>}
                </div>
                <h1 style={{
                  margin:"8px 0 0",
                  fontFamily:window.ASX.font,
                  fontSize:42, fontWeight:800, letterSpacing:"-0.03em", color:"#071e47",
                  lineHeight:1.05,
                }}>{msp.name}</h1>
              </div>
            </div>
            <p style={{fontSize:17, color:"#39466A", lineHeight:1.5, margin:0, maxWidth:600}}>
              {msp.tagline}.
            </p>

            <div style={{marginTop:24, display:"flex", flexWrap:"wrap", gap:20, fontSize:13, color:"#39466A"}}>
              <Fact icon="map-pin" value={`${msp.city}, ${msp.region}`}/>
              <Fact icon="building" value={`Founded ${msp.founded}`}/>
              <Fact icon="users" value={`${msp.headcount} people`}/>
              <Fact icon="shield" value={`${msp.clients} clients managed`}/>
            </div>

            <div style={{marginTop:28, display:"flex", gap:10}}>
              <a href={`https://${msp.contacts.web}`} target="_blank" rel="noreferrer" style={primaryBtn}>
                Visit {msp.name} <Icon name="external" size={14}/>
              </a>
              <button style={ghostBtn}>
                <Icon name="share" size={14}/> Share profile
              </button>
            </div>
          </div>

          {/* Trustmark */}
          <div style={{display:"flex", flexDirection:"column", alignItems:"center", gap:8}}>
            <BlockMark variant={isTrusted?"trusted":"journey"} size={230} name={msp.name} blockmarkId={msp.blockmarkId}/>
            <div style={{marginTop:18, textAlign:"center"}}>
              <div style={{
                display:"inline-flex", alignItems:"center", gap:6,
                background:"#E6FAF3", color:"#137F70",
                padding:"5px 11px 5px 9px", borderRadius:999,
                fontSize:12, fontWeight:700, letterSpacing:"-0.005em",
              }}>
                <span style={{position:"relative", width:8, height:8}}>
                  <span style={{position:"absolute", inset:0, borderRadius:99, background:"#2a9d8f"}}/>
                  <span style={{position:"absolute", inset:-3, borderRadius:99, background:"#2a9d8f", opacity:0.25, animation:"asx-pulse 2s ease-out infinite"}}/>
                </span>
                Verified
              </div>
              <div style={{marginTop:8, fontSize:11, color:"#6B7793", lineHeight:1.5}}>
                Auto-rechecked every 6 hours · last check {fmtRel(msp.lastVerified)}
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* Main content */}
      <div style={{maxWidth:1320, margin:"0 auto", padding:"40px 32px", display:"grid", gridTemplateColumns:"1fr 340px", gap:40}}>
        <main style={{display:"flex", flexDirection:"column", gap:28}}>
          <Panel title="About" subtitle={`What ${msp.name} is best known for`}>
            <p style={{margin:0, fontSize:15, lineHeight:1.6, color:"#39466A", textWrap:"pretty"}}>
              {msp.about}
            </p>
          </Panel>

          <Panel title="Specialisms & industries">
            <SpecsPanel msp={msp}/>
          </Panel>
        </main>

        {/* Right rail */}
        <aside style={{display:"flex", flexDirection:"column", gap:20, position:"sticky", top:80, alignSelf:"start"}}>
          <ContactCard msp={msp} onContact={()=>setContactOpen(true)}/>
          <CertsCard msp={msp}/>
          <SimilarCard current={msp}/>
        </aside>
      </div>
    </div>
  );
}

// ---------------------------------------------------------------------------
function Fact({ icon, value }) {
  return (
    <span style={{display:"inline-flex", alignItems:"center", gap:6}}>
      <Icon name={icon} size={14} color="#6B7793"/> {value}
    </span>
  );
}

function Panel({ title, subtitle, children }) {
  return (
    <section style={{
      background:"#fff", border:"1px solid #E4E9F2", borderRadius:16,
      padding:"24px 26px",
    }}>
      <header style={{marginBottom:18}}>
        <div style={{fontSize:16, fontWeight:700, color:"#071e47", letterSpacing:"-0.01em"}}>{title}</div>
        {subtitle && <div style={{fontSize:12, color:"#6B7793", marginTop:2}}>{subtitle}</div>}
      </header>
      {children}
    </section>
  );
}

// ---------- Verification proof ---------------------------------------------
function VerificationProof({ msp }) {
  const controls = [
    { group:"Identity & access",  total:4, verified: msp.stage==="trusted" ? 4 : 3 },
    { group:"Endpoint hardening", total:5, verified: msp.stage==="trusted" ? 5 : 4 },
    { group:"Backup & recovery",  total:3, verified: msp.stage==="trusted" ? 3 : 2 },
    { group:"Monitoring & SOC",   total:4, verified: msp.stage==="trusted" ? 4 : 2 },
    { group:"Change management",  total:3, verified: msp.stage==="trusted" ? 3 : 2 },
    { group:"Vendor oversight",   total:3, verified: msp.stage==="trusted" ? 3 : 1 },
  ];
  const totalV = controls.reduce((s,c)=>s+c.verified, 0);
  const totalT = controls.reduce((s,c)=>s+c.total, 0);

  return (
    <div>
      <div style={{display:"grid", gridTemplateColumns:"1fr 1fr", gap:14, marginBottom:18}}>
        <KPI label="Controls verified" value={`${totalV} / ${totalT}`} sub={`${Math.round(totalV/totalT*100)}%`} tone="good"/>
        <KPI label="Continuous monitoring" value="Connected" sub={`PSA · RMM · M365`} tone="good"/>
        <KPI label="Evidence freshness" value={fmtRel(msp.lastVerified)} sub="Auto re-checked daily" tone="neutral"/>
      </div>

      <div style={{display:"flex", flexDirection:"column", gap:8}}>
        {controls.map(c => (
          <div key={c.group} style={{display:"grid", gridTemplateColumns:"180px 1fr 70px", alignItems:"center", gap:14}}>
            <div style={{fontSize:13, color:"#071e47", fontWeight:500}}>{c.group}</div>
            <div style={{background:"#F0F3F8", height:8, borderRadius:99, overflow:"hidden"}}>
              <div style={{
                height:"100%",
                width: `${c.verified/c.total*100}%`,
                background: c.verified === c.total ? "#2a9d8f" : "#b8d645",
                borderRadius:99,
              }}/>
            </div>
            <div style={{fontSize:12, color:"#39466A", fontVariantNumeric:"tabular-nums", textAlign:"right"}}>
              {c.verified}/{c.total}
              {c.verified===c.total && <Icon name="check" size={12} color="#2a9d8f" strokeWidth={3}/>}
            </div>
          </div>
        ))}
      </div>

      <div style={{marginTop:18, padding:14, background:"#F4F7FB", borderRadius:10, fontSize:12, color:"#39466A", display:"flex", gap:10, alignItems:"flex-start"}}>
        <Icon name="shield" size={14} color="#2a9d8f"/>
        <div>
          Evidence is gathered automatically from {msp.name}'s PSA, RMM and Microsoft 365 tenant. Assurix never stores credentials — we observe read-only telemetry via OAuth and normalise it into the control evidence shown here.
        </div>
      </div>
    </div>
  );
}

function KPI({ label, value, sub, tone }) {
  const color = tone === "good" ? "#2a9d8f" : "#39466A";
  return (
    <div style={{border:"1px solid #E4E9F2", borderRadius:12, padding:"14px 16px"}}>
      <div style={{fontSize:11, color:"#6B7793", textTransform:"uppercase", letterSpacing:"0.05em", fontWeight:600}}>{label}</div>
      <div style={{fontSize:22, fontWeight:700, color:"#071e47", letterSpacing:"-0.02em", marginTop:6}}>{value}</div>
      <div style={{fontSize:11, color, marginTop:2}}>{sub}</div>
    </div>
  );
}

// ---------- Journey timeline ------------------------------------------------
function Timeline({ msp }) {
  const events = [
    { d:"2025-06-14", title:"Enrolled", body:"Initial assessment booked via partner channel" },
    { d:"2025-07-22", title:"Stage 1 assessment",  body:"Control evidence collected across 6 domains" },
    { d:"2025-08-30", title:"Stage 2 verification", body:"Auditor interviews · ISO 27001 scope confirmed" },
    { d: msp.issuedAt, title:"BlockMark issued", body: msp.stage==="trusted" ? "Trusted MSP tier — all 22 controls verified" : "On the Journey tier — improvement plan active" },
    { d: msp.lastVerified, title:"Continuous re-check", body:"Automated telemetry matches expected controls" },
  ];
  return (
    <ol style={{listStyle:"none", padding:0, margin:0, position:"relative"}}>
      <div style={{position:"absolute", left:7, top:8, bottom:8, width:2, background:"#E4E9F2"}}/>
      {events.map((e,i)=>{
        const done = new Date(e.d) <= new Date("2026-04-17");
        const isLast = i === events.length - 1;
        return (
          <li key={i} style={{position:"relative", paddingLeft:34, paddingBottom: isLast?0:18}}>
            <span style={{
              position:"absolute", left:0, top:2,
              width:16, height:16, borderRadius:99,
              background: done ? "#2a9d8f" : "#fff",
              border:`2px solid ${done?"#2a9d8f":"#E4E9F2"}`,
              display:"flex", alignItems:"center", justifyContent:"center",
            }}>
              {done && <Icon name="check" size={9} color="#fff" strokeWidth={3.5}/>}
            </span>
            <div style={{fontSize:13, fontWeight:600, color:"#071e47"}}>{e.title}</div>
            <div style={{fontSize:11, color:"#6B7793", fontFamily:"'JetBrains Mono', ui-monospace, monospace", marginTop:2}}>{fmtDate(e.d)}</div>
            <div style={{fontSize:13, color:"#39466A", marginTop:4}}>{e.body}</div>
          </li>
        );
      })}
    </ol>
  );
}

// ---------- Specs -----------------------------------------------------------
function SpecsPanel({ msp }) {
  return (
    <div style={{display:"grid", gridTemplateColumns:"1fr 1fr", gap:24}}>
      <div>
        <div style={{fontSize:12, color:"#6B7793", textTransform:"uppercase", letterSpacing:"0.05em", fontWeight:600, marginBottom:10}}>Industries served</div>
        <div style={{display:"flex", flexWrap:"wrap", gap:6}}>
          {msp.industries.map(i => <span key={i} style={chipStyle}>{i}</span>)}
        </div>
      </div>
      <div>
        <div style={{fontSize:12, color:"#6B7793", textTransform:"uppercase", letterSpacing:"0.05em", fontWeight:600, marginBottom:10}}>Technology specialisms</div>
        <div style={{display:"flex", flexWrap:"wrap", gap:6}}>
          {msp.specialisms.map(s => <span key={s} style={chipStyle}>{s}</span>)}
        </div>
      </div>
    </div>
  );
}

// ---------- Right rail ------------------------------------------------------
function ContactCard({ msp, onContact }) {
  return (
    <div style={{background:"#fff", border:"1px solid #E4E9F2", borderRadius:16, padding:"20px 22px"}}>
      <div style={{fontSize:14, fontWeight:700, color:"#071e47", marginBottom:14}}>Get in touch</div>
      <div style={{display:"flex", flexDirection:"column", gap:10, fontSize:13, color:"#39466A"}}>
        <a href={`https://${msp.contacts.web}`} style={{color:"#39466A", textDecoration:"none", display:"flex", alignItems:"center", gap:10}}>
          <Icon name="globe" size={14} color="#6B7793"/> {msp.contacts.web}
        </a>
        <a href={`mailto:${msp.contacts.email}`} style={{color:"#39466A", textDecoration:"none", display:"flex", alignItems:"center", gap:10}}>
          <Icon name="mail" size={14} color="#6B7793"/> {msp.contacts.email}
        </a>
        <a href={`tel:${msp.contacts.phone}`} style={{color:"#39466A", textDecoration:"none", display:"flex", alignItems:"center", gap:10}}>
          <Icon name="phone" size={14} color="#6B7793"/> {msp.contacts.phone}
        </a>
      </div>
      <button onClick={onContact} style={{...primaryBtn, width:"100%", justifyContent:"center", marginTop:16}}>
        Contact {msp.name} <Icon name="arrow-right" size={13}/>
      </button>
      <div style={{marginTop:8, fontSize:11, color:"#6B7793", textAlign:"center", lineHeight:1.4}}>
        We'll send your details to {msp.name} as a lead in their PSA / CRM.
      </div>
    </div>
  );
}

function ContactModal({ msp, onClose }) {
  const [submitted, setSubmitted] = useStateP(false);
  const [form, setForm] = useStateP({ name:"", company:"", email:"", phone:"", vertical:"", message:"" });
  const set = (k) => (e) => setForm({...form, [k]: e.target.value});
  const valid = form.name.trim() && form.email.trim() && form.company.trim();
  const submit = (e) => { e.preventDefault(); if (!valid) return; setSubmitted(true); };

  const overlay = {
    position:"fixed", inset:0, background:"rgba(7,30,71,0.55)", backdropFilter:"blur(6px)",
    display:"flex", alignItems:"center", justifyContent:"center", padding:24, zIndex:1000,
  };
  const card = {
    background:"#fff", borderRadius:18, width:"100%", maxWidth:520,
    padding:"28px 28px 24px", boxShadow:"0 20px 60px rgba(7,30,71,0.35)",
  };
  const lbl = { fontSize:12, color:"#6B7793", fontWeight:600, textTransform:"uppercase", letterSpacing:"0.05em", marginBottom:6, display:"block" };
  const inp = {
    width:"100%", border:"1px solid #E4E9F2", borderRadius:10, padding:"10px 12px",
    fontSize:14, fontFamily:"inherit", color:"#071e47", background:"#F8FAFD", outline:"none",
  };

  if (submitted) {
    return (
      <div style={overlay} onClick={onClose}>
        <div style={card} onClick={e=>e.stopPropagation()}>
          <div style={{display:"flex", justifyContent:"center", marginBottom:16}}>
            <span style={{
              width:56, height:56, borderRadius:99, background:"#E6FAF3",
              display:"inline-flex", alignItems:"center", justifyContent:"center",
            }}>
              <Icon name="check" size={28} color="#2a9d8f" strokeWidth={3}/>
            </span>
          </div>
          <h2 style={{margin:0, fontSize:22, fontWeight:800, letterSpacing:"-0.02em", color:"#071e47", textAlign:"center"}}>
            Thanks — we've contacted {msp.name}
          </h2>
          <p style={{margin:"10px 0 0", fontSize:14, color:"#39466A", lineHeight:1.55, textAlign:"center"}}>
            Your details have been sent as a lead in {msp.name}'s PSA. Expect to hear back within 1 working day. We've copied you in at <b>{form.email}</b>.
          </p>
          <button onClick={onClose} style={{...primaryBtn, width:"100%", justifyContent:"center", marginTop:22}}>
            Done
          </button>
        </div>
      </div>
    );
  }

  return (
    <div style={overlay} onClick={onClose}>
      <form style={card} onClick={e=>e.stopPropagation()} onSubmit={submit}>
        <div style={{display:"flex", justifyContent:"space-between", alignItems:"flex-start", marginBottom:6}}>
          <div>
            <div style={{fontSize:11, color:"#6B7793", fontWeight:600, textTransform:"uppercase", letterSpacing:"0.06em"}}>
              Contact MSP
            </div>
            <h2 style={{margin:"4px 0 0", fontSize:22, fontWeight:800, letterSpacing:"-0.02em", color:"#071e47"}}>
              {msp.name}
            </h2>
          </div>
          <button type="button" onClick={onClose} aria-label="Close" style={{
            border:"none", background:"#F0F3F8", borderRadius:99, width:30, height:30,
            display:"inline-flex", alignItems:"center", justifyContent:"center", cursor:"pointer",
          }}>
            <Icon name="x" size={14} color="#39466A"/>
          </button>
        </div>
        <p style={{margin:"4px 0 18px", fontSize:13, color:"#5C6784", lineHeight:1.5}}>
          We'll send your details directly to {msp.name} as a qualified lead in their PSA / CRM. They'll be in touch within 1 working day.
        </p>

        <div style={{display:"grid", gridTemplateColumns:"1fr 1fr", gap:12}}>
          <div>
            <label style={lbl}>Your name *</label>
            <input style={inp} value={form.name} onChange={set("name")} required/>
          </div>
          <div>
            <label style={lbl}>Company *</label>
            <input style={inp} value={form.company} onChange={set("company")} required/>
          </div>
          <div>
            <label style={lbl}>Work email *</label>
            <input style={inp} type="email" value={form.email} onChange={set("email")} required/>
          </div>
          <div>
            <label style={lbl}>Phone</label>
            <input style={inp} type="tel" value={form.phone} onChange={set("phone")}/>
          </div>
          <div style={{gridColumn:"1 / -1"}}>
            <label style={lbl}>Your industry</label>
            <select style={inp} value={form.vertical} onChange={set("vertical")}>
              <option value="">Select your industry…</option>
              {window.INDUSTRIES.map(i => <option key={i} value={i}>{i}</option>)}
            </select>
          </div>
          <div style={{gridColumn:"1 / -1"}}>
            <label style={lbl}>What do you need help with?</label>
            <textarea style={{...inp, minHeight:80, resize:"vertical", fontFamily:"inherit"}} value={form.message} onChange={set("message")}/>
          </div>
        </div>

        <button type="submit" disabled={!valid} style={{
          ...primaryBtn, width:"100%", justifyContent:"center", marginTop:18,
          opacity: valid ? 1 : 0.5, cursor: valid ? "pointer" : "not-allowed",
        }}>
          Send to {msp.name} <Icon name="arrow-right" size={13}/>
        </button>
        <div style={{marginTop:10, fontSize:11, color:"#6B7793", textAlign:"center", lineHeight:1.5}}>
          By contacting this MSP you agree that Assurix may share your details with {msp.name} for the purpose of responding to your enquiry.
        </div>
      </form>
    </div>
  );
}

function CertsCard({ msp }) {
  return (
    <div style={{background:"#fff", border:"1px solid #E4E9F2", borderRadius:16, padding:"20px 22px"}}>
      <div style={{fontSize:14, fontWeight:700, color:"#071e47", marginBottom:14}}>Certifications</div>
      <ul style={{listStyle:"none", padding:0, margin:0, display:"flex", flexDirection:"column", gap:8}}>
        {msp.certifications.map(c => (
          <li key={c} style={{display:"flex", alignItems:"center", gap:10, fontSize:13, color:"#39466A"}}>
            <span style={{width:22, height:22, borderRadius:6, background:"#E6FAF3", display:"flex", alignItems:"center", justifyContent:"center"}}>
              <Icon name="check" size={12} color="#2a9d8f" strokeWidth={3}/>
            </span>
            {c}
          </li>
        ))}
      </ul>
    </div>
  );
}

function SimilarCard({ current }) {
  const similar = window.MSPS
    .filter(m => m.slug !== current.slug && m.region === current.region)
    .slice(0, 3);
  if (similar.length === 0) return null;
  return (
    <div style={{background:"#fff", border:"1px solid #E4E9F2", borderRadius:16, padding:"20px 22px"}}>
      <div style={{fontSize:14, fontWeight:700, color:"#071e47", marginBottom:14}}>Nearby Trusted MSPs</div>
      <div style={{display:"flex", flexDirection:"column", gap:12}}>
        {similar.map(m => (
          <a key={m.slug} href={`#/${m.slug}`} style={{
            display:"flex", alignItems:"center", gap:10,
            textDecoration:"none", color:"inherit",
          }}>
            <MspMark msp={m} size={32}/>
            <div style={{flex:1, minWidth:0}}>
              <div style={{fontSize:13, fontWeight:600, color:"#071e47"}}>{m.name}</div>
              <div style={{fontSize:11, color:"#6B7793"}}>{m.city}</div>
            </div>
            <StageChip stage={m.stage} small/>
          </a>
        ))}
      </div>
    </div>
  );
}

function fmtDate(iso) {
  return new Date(iso).toLocaleDateString("en-GB", { day:"numeric", month:"short", year:"numeric" });
}

Object.assign(window, { ProfileView, fmtDate });
