/* CourseDetail - University Prospectus layout
   Qualification-first · providers inline at bottom. */

/* ── Stars ── */
function CDStars({ rating, count }) {
  return (
    <span style={{ display:"inline-flex", alignItems:"center", gap:4 }}>
      <Icon name="star" size={13} style={{ color:"var(--tr-amber-500)", fill:"var(--tr-amber-500)" }}/>
      <b style={{ fontSize:13.5, color:"var(--tr-ink)" }}>{rating.toFixed(1)}</b>
      {count && <span style={{ fontSize:12, color:"var(--tr-fg-muted)" }}>({count})</span>}
    </span>
  );
}

/* ── Horizontal fact chip (fact strip) ── */
function CDFactChip({ label, value, icon, last }) {
  return (
    <div style={{ display:"flex", flexDirection:"column", gap:5, padding:"14px 20px", borderRight: last?"none":"1px solid var(--tr-brand-200)", flexShrink:0, minWidth:110 }}>
      <span style={{ fontSize:10.5, fontWeight:700, textTransform:"uppercase", letterSpacing:"0.1em", color:"var(--tr-brand-700)", display:"flex", alignItems:"center", gap:4 }}>
        <Icon name={icon} size={11}/> {label}
      </span>
      {value
        ? <span style={{ fontSize:14, fontWeight:600, color:"var(--tr-ink)" }}>{value}</span>
        : <span style={{ fontSize:13, color:"var(--tr-fg-faint)", fontStyle:"italic" }}>-</span>
      }
    </div>
  );
}

/* ── Section block ── */
function CDSection({ eyebrow, children, last }) {
  return (
    <div style={{ marginBottom:last?0:36, paddingBottom:last?0:36, borderBottom:last?"none":"1px solid var(--tr-line-2)" }}>
      {eyebrow && (
        <div style={{ fontSize:11, fontWeight:700, textTransform:"uppercase", letterSpacing:"0.12em", color:"var(--tr-fg-muted)", marginBottom:12 }}>{eyebrow}</div>
      )}
      {children}
    </div>
  );
}

/* ── Right for you / Skip it ── */
function CDFitCols({ rightFor, notFor }) {
  if (!rightFor) return (
    <div style={{ padding:"14px 16px", background:"var(--tr-paper-2)", borderRadius:10, fontSize:13.5, color:"var(--tr-fg-muted)", display:"flex", gap:9, alignItems:"flex-start" }}>
      <Icon name="info" size={15} style={{ flexShrink:0, marginTop:1 }}/>
      <span>Not published by this awarding body. Check their site for suitability guidance.</span>
    </div>
  );
  return (
    <div style={{ display:"grid", gridTemplateColumns:"1fr 1fr", gap:12 }}>
      {[
        { tone:"good", head:"Right for you if", items:rightFor, icon:"check" },
        { tone:"bad",  head:"Skip it if",       items:notFor,  icon:"x"     },
      ].map(({ tone, head, items, icon }) => (
        <div key={head} style={{ background:tone==="good"?"var(--tr-brand-50)":"var(--tr-paper-2)", border:`1px solid ${tone==="good"?"var(--tr-brand-100)":"var(--tr-line)"}`, borderRadius:12, padding:16 }}>
          <div style={{ fontFamily:"var(--tr-font-display)", fontWeight:700, fontSize:13.5, color:tone==="good"?"var(--tr-brand-700)":"var(--tr-ink-2)", marginBottom:11, display:"flex", alignItems:"center", gap:6 }}>
            <Icon name={icon} size={14} stroke={2.5}/> {head}
          </div>
          <ul style={{ listStyle:"none", margin:0, padding:0, display:"flex", flexDirection:"column", gap:9 }}>
            {items.map(t => (
              <li key={t} style={{ display:"flex", gap:8, fontSize:13.5, lineHeight:1.45, color:"var(--tr-fg-2)" }}>
                <Icon name={icon} size={14} stroke={2.5} style={{ color:tone==="good"?"var(--tr-brand-500)":"var(--tr-fg-faint)", flexShrink:0, marginTop:1 }}/>
                {t}
              </li>
            ))}
          </ul>
        </div>
      ))}
    </div>
  );
}

/* ── Syllabus grid ── */
function CDSyllabus({ covers }) {
  if (!covers || covers.length === 0) return (
    <div style={{ padding:"14px 16px", background:"var(--tr-paper-2)", borderRadius:10, fontSize:13.5, color:"var(--tr-fg-muted)" }}>
      Syllabus not published - check the awarding body's site for full learning outcomes.
    </div>
  );
  return (
    <div style={{ display:"grid", gridTemplateColumns:"1fr 1fr", gap:7 }}>
      {covers.map(c => (
        <div key={c} style={{ display:"flex", alignItems:"center", gap:8, padding:"9px 12px", background:"var(--tr-paper-2)", borderRadius:8, fontSize:13.5, color:"var(--tr-ink)" }}>
          <Icon name="check" size={13} stroke={2.5} style={{ color:"var(--tr-brand-500)", flexShrink:0 }}/> {c}
        </div>
      ))}
    </div>
  );
}

/* ── Provider card ── */
function CDProviderCard({ row }) {
  const isOnline = /online/i.test(row.format || "");
  return (
    <div style={{ border:row.best?"1.5px solid var(--tr-brand-400)":"1px solid var(--tr-line)", borderRadius:14, padding:18, background:row.best?"var(--tr-brand-50)":"#fff", position:"relative", display:"flex", flexDirection:"column" }}>
      {row.best && (
        <div style={{ position:"absolute", top:-10, left:14 }}>
          <span className="tr-pill tr-pill-amber" style={{ fontSize:10.5 }}>Lowest price</span>
        </div>
      )}

      {/* name + price */}
      <div style={{ display:"flex", justifyContent:"space-between", alignItems:"flex-start", marginBottom:12, gap:10 }}>
        <div>
          <div style={{ fontFamily:"var(--tr-font-display)", fontWeight:700, fontSize:15.5, color:"var(--tr-ink)", marginBottom:3, lineHeight:1.2 }}>{row.provider}</div>
          <div style={{ fontSize:12.5, color:"var(--tr-fg-muted)", display:"flex", alignItems:"center", gap:4 }}>
            <Icon name={isOnline?"globe":"map-pin"} size={12}/> {row.location}
          </div>
        </div>
        <div style={{ textAlign:"right", flexShrink:0 }}>
          <div style={{ fontFamily:"var(--tr-font-mono)", fontSize:19, fontWeight:600, color:"var(--tr-ink)", letterSpacing:"-0.02em" }}>{row.price}</div>
          {row.rating && <CDStars rating={row.rating} count={row.n}/>}
        </div>
      </div>

      {/* key facts */}
      <div style={{ display:"grid", gridTemplateColumns:"1fr 1fr", gap:"6px 14px", marginBottom:14, fontSize:13, flex:1 }}>
        <div><span style={{ color:"var(--tr-fg-muted)", marginRight:4 }}>Format</span>{row.format}</div>
        <div><span style={{ color:"var(--tr-fg-muted)", marginRight:4 }}>Duration</span>{row.duration}</div>
        <div><span style={{ color:"var(--tr-fg-muted)", marginRight:4 }}>Next</span><span style={{ color:"var(--tr-brand-700)", fontWeight:600 }}>{row.next}</span></div>
        <div>
          <span className={"tr-pill " + (row.tight?"tr-pill-amber":"tr-pill-neutral")} style={{ fontSize:10.5 }}>{row.spots}</span>
        </div>
      </div>

      {/* CTA */}
      <div style={{ padding:"10px 0", background:row.best?"var(--tr-brand-500)":"transparent", border:row.best?"none":"1.5px solid var(--tr-line)", borderRadius:9, textAlign:"center", fontSize:13.5, fontWeight:600, color:row.best?"#fff":"var(--tr-ink)", cursor:"pointer" }}>
        View this provider →
      </div>
    </div>
  );
}

/* ══════════════════════════════════════════════
   Main component
══════════════════════════════════════════════ */
/* Map a raw published qual (from /api/quals, stored in DETAIL_BY_ID) into the
   shape this detail page renders. No fabricated fields - empty stays empty. */
function qualToDetail(q) {
  if (!q) return null;
  function splitList(s) {
    if (!s) return [];
    return String(s).split(/\n|•|;|\u2022/).map(x => x.trim()).filter(Boolean);
  }
  var facts = [];
  if (q.qualification_level) facts.push({ label: "Level", value: q.qualification_level, icon: "award" });
  if (q.glh) facts.push({ label: "GLH", value: String(q.glh), icon: "clock" });
  if (q.tqt) facts.push({ label: "TQT", value: String(q.tqt), icon: "clock" });
  if (q.ofqual_number) facts.push({ label: "Ofqual", value: q.ofqual_number, icon: "badge-check" });
  return {
    title: q.qualification_title || "",
    level: q.qualification_level || "",
    career: "",
    body: q.awarder || "",
    summary: q.overview || "",
    qualifies: q.certification_earned || "",
    rightFor: [], notFor: [],
    covers: splitList(q.course_structure),
    entry: q.entry_requirements || "",
    ofqual: q.ofqual_number || "",
    qualFacts: facts,
    verdict: q.global_recognition_plain || "",
    verifyBody: q.awarder || "",
    verifyUrl: (q.source_url || q.source_url2 || "").replace(/^https?:\/\//, ""),
    status: q.current_status || ""
  };
}

function CourseDetail({ courseId, onNavigate, onOpenChat }) {
  const byId = window.TR_CONTENT.DETAIL_BY_ID || {};
  const raw = courseId && byId[courseId] ? byId[courseId] : null;
  const d = raw ? qualToDetail(raw) : window.TR_CONTENT.DETAIL;

  // providers: our published quals don't carry COMPARE rows yet -> empty, guarded
  const C = (raw ? { rows: [] } : window.TR_CONTENT.COMPARE) || { rows: [] };

  /* price range for header */
  const prices = (C.rows || []).map(r => parseInt((r.price || "").replace(/[^0-9]/g, ""))).filter(Boolean);
  const priceRange = prices.length ? `AED ${Math.min(...prices).toLocaleString()} - ${Math.max(...prices).toLocaleString()}` : null;

  return (
    <main style={{ background:"#fff" }}>

      {/* ── Back breadcrumb ── */}
      <div className="container" style={{ padding:"14px var(--tr-gutter) 0" }}>
        <button className="tr-btn tr-btn-ghost tr-btn-sm" onClick={() => onNavigate("home")} style={{ padding:"6px 0", color:"var(--tr-fg-muted)", fontSize:13.5 }}>
          <Icon name="arrow-left" size={15}/> Back to courses
        </button>
      </div>

      {/* ══ HEADER ZONE - brand-50 background ══ */}
      <div style={{ background:"var(--tr-brand-50)", borderBottom:"1px solid var(--tr-brand-100)", marginTop:8 }}>
        <div className="container" style={{ padding:"24px var(--tr-gutter) 0" }}>

          {/* pills */}
          <div style={{ display:"flex", gap:7, flexWrap:"wrap", marginBottom:14, alignItems:"center" }}>
            <span className="tr-pill tr-pill-approved" style={{ display:"inline-flex", alignItems:"center", gap:5, fontSize:11.5 }}>
              <Icon name="badge-check" size={12}/> REPs UAE approved
            </span>
            <span className="tr-pill tr-pill-neutral" style={{ fontSize:11.5 }}>{d.level}</span>
            <span className="tr-pill tr-pill-neutral" style={{ fontSize:11.5 }}>{d.career}</span>
          </div>

          {/* title */}
          <h1 style={{ fontFamily:"var(--tr-font-display)", fontWeight:700, fontSize:"clamp(26px, 3.5vw, 42px)", lineHeight:1.07, letterSpacing:"-0.03em", margin:"0 0 12px", color:"var(--tr-ink)", textWrap:"balance", maxWidth:700 }}>
            {d.title}
          </h1>

          {/* sub-line */}
          <div style={{ fontSize:14.5, color:"var(--tr-fg-muted)", display:"flex", alignItems:"center", gap:8, flexWrap:"wrap", paddingBottom:20 }}>
            <span>Awarded by <strong style={{ color:"var(--tr-ink-2)", fontWeight:600 }}>{d.body}</strong></span>
            {d.ofqual && (
              <>
                <span style={{ color:"var(--tr-brand-200)" }}>·</span>
                <span>Ofqual <code style={{ fontFamily:"var(--tr-font-mono)", fontSize:12.5, background:"rgba(255,255,255,0.7)", padding:"1px 6px", borderRadius:4, color:"var(--tr-ink-2)", border:"1px solid var(--tr-brand-200)" }}>{d.ofqual}</code></span>
              </>
            )}
          </div>
        </div>

        {/* fact strip - scrollable on mobile */}
        <div style={{ borderTop:"1px solid var(--tr-brand-100)", overflowX:"auto", WebkitOverflowScrolling:"touch" }}>
          <div className="container" style={{ display:"flex", padding:"0 var(--tr-gutter)", minWidth:"max-content" }}>
            {(d.qualFacts || []).map((f, i) => (
              <CDFactChip key={f.label} label={f.label} value={f.value} icon={f.icon} last={i === d.qualFacts.length - 1}/>
            ))}
          </div>
        </div>
      </div>

      {/* ══ STATUS NOTICE - honest flag for discontinued / closing courses ══ */}
      {(function () {
        var st = (d.status || "").toLowerCase();
        if (!st || st === "active" || st === "available_to_learners" || st === "active_standards_framework") return null;
        var title, body;
        var dm = st.match(/(\d{4}-\d{2}-\d{2})/); var date = dm ? dm[1] : "";
        if (st.indexOf("archiv") > -1 || st.indexOf("no_longer_awarded") > -1) {
          title = "Discontinued - no longer available to new learners";
          body = "The awarding body has withdrawn this qualification, so you can no longer enrol on it. We list it for reference. What this means for you: do not pay any provider for this course. Choose a current qualification of the same level and role so it is accepted for REPs UAE registration. Anyone who already completed it keeps their certificate, it does not expire.";
        } else if (st.indexOf("withdrawal_announced") > -1) {
          title = "Being withdrawn" + (date ? " (closes " + date + ")" : "");
          body = "New registrations close" + (date ? " on " + date : " soon") + ". You can still enrol before then, and current learners can finish.";
        } else if (st.indexOf("withdrawn_new") > -1 || st.indexOf("no_new_registrations") > -1) {
          title = "Closed to new students" + (date ? " (from " + date + ")" : "");
          body = "The awarding body has stopped accepting new learners. Those already enrolled can still complete it.";
        } else { title = d.status; body = ""; }
        return (
          <div className="container-narrow" style={{ padding:"24px var(--tr-gutter) 0" }}>
            <div style={{ background:"#FFF0D6", border:"1px solid #F0C674", borderLeft:"5px solid #C98800", borderRadius:10, padding:"14px 16px" }}>
              <div style={{ display:"flex", alignItems:"center", gap:8, fontWeight:800, fontSize:15, color:"#8A4B00" }}>
                <Icon name="info" size={16}/> {title}
              </div>
              {body && <div style={{ fontSize:14, lineHeight:1.55, color:"#7A5200", marginTop:5 }}>{body}</div>}
            </div>
          </div>
        );
      })()}

      {/* ══ BODY - single column, narrow ══ */}
      <div className="container-narrow" style={{ padding:"40px var(--tr-gutter) 0" }}>

        <CDSection eyebrow="Overview">
          <p style={{ fontSize:16.5, lineHeight:1.7, color:"var(--tr-fg-2)", margin:0, textWrap:"pretty" }}>{d.summary}</p>
        </CDSection>

        <CDSection eyebrow="What it lets you do in the UAE">
          <div style={{ background:"var(--tr-brand-50)", border:"1px solid var(--tr-brand-100)", borderRadius:12, padding:"16px 18px", display:"flex", gap:13 }}>
            <Icon name="shield-check" size={20} style={{ color:"var(--tr-brand-600)", flexShrink:0, marginTop:2 }}/>
            <p style={{ margin:0, fontSize:15, lineHeight:1.6, color:"var(--tr-fg-2)", textWrap:"pretty" }}>{d.qualifies}</p>
          </div>
        </CDSection>

        <CDSection eyebrow="Is this the right course for you?">
          <CDFitCols rightFor={d.rightFor} notFor={d.notFor}/>
        </CDSection>

        <CDSection eyebrow="What's actually covered">
          <CDSyllabus covers={d.covers}/>
        </CDSection>

        <CDSection eyebrow="Entry requirements" last>
          {d.entry
            ? <p style={{ margin:0, fontSize:14.5, lineHeight:1.65, color:"var(--tr-fg-2)" }}>{d.entry}</p>
            : <p style={{ margin:0, fontSize:13.5, color:"var(--tr-fg-muted)", fontStyle:"italic" }}>Not published - check the awarding body's site for details.</p>
          }
        </CDSection>
      </div>

      {/* ══ PROVIDER SECTION - full width, paper-2 ══ */}
      <div style={{ background:"var(--tr-paper-2)", borderTop:"1px solid var(--tr-line-2)", padding:"40px 0 48px", marginTop:40 }}>
        <div className="container">

          {/* section header */}
          <div style={{ display:"flex", alignItems:"flex-end", justifyContent:"space-between", marginBottom:24, flexWrap:"wrap", gap:12 }}>
            <div>
              <div style={{ fontSize:11, fontWeight:700, textTransform:"uppercase", letterSpacing:"0.12em", color:"var(--tr-fg-muted)", marginBottom:6 }}>
                Study this qualification with a provider
              </div>
              <h2 style={{ fontFamily:"var(--tr-font-display)", fontWeight:700, fontSize:28, letterSpacing:"-0.02em", margin:0, color:"var(--tr-ink)" }}>
                {C.rows.length ? C.rows.length + " providers. Same certificate." : "Providers, coming soon."}
              </h2>
            </div>
            <div style={{ display:"flex", gap:12, alignItems:"center", flexWrap:"wrap" }}>
              {priceRange && (
                <span style={{ fontFamily:"var(--tr-font-mono)", fontSize:13.5, color:"var(--tr-fg-2)" }}>{priceRange} all-in</span>
              )}
              <button className="tr-btn tr-btn-ghost tr-btn-sm" onClick={onOpenChat}>
                <Icon name="sparkles" size={14}/> Ask which suits you
              </button>
            </div>
          </div>

          {/* provider cards (or honest empty state) */}
          {C.rows.length ? (
            <div style={{ display:"grid", gridTemplateColumns:"repeat(auto-fill, minmax(240px, 1fr))", gap:14 }}>
              {C.rows.map(r => <CDProviderCard key={r.provider} row={r}/>)}
            </div>
          ) : (
            <p style={{ margin:0, fontSize:14.5, lineHeight:1.6, color:"var(--tr-fg-2)" }}>
              We're verifying which UAE providers deliver this qualification and at what price. Ask us and we'll point you to the right one.
            </p>
          )}

          <p style={{ marginTop:20, marginBottom:0, fontSize:13, color:"var(--tr-fg-muted)", textAlign:"center" }}>
            We don't sell courses. Provider listings are for your convenience - we earn nothing from enrolments.
          </p>
        </div>
      </div>

      {/* ══ VERIFY AT SOURCE ══ */}
      <div style={{ background:"#fff", borderTop:"1px solid var(--tr-line-2)", padding:"28px 0 72px" }}>
        <div className="container-narrow" style={{ padding:"0 var(--tr-gutter)" }}>
          <div style={{ border:"1px solid var(--tr-line)", borderRadius:12, padding:"18px 20px", display:"flex", alignItems:"center", gap:20, justifyContent:"space-between", flexWrap:"wrap" }}>
            <div style={{ flex:1, minWidth:220 }}>
              <div style={{ fontSize:11, fontWeight:700, textTransform:"uppercase", letterSpacing:"0.1em", color:"var(--tr-fg-muted)", marginBottom:5 }}>Verify at source</div>
              <div style={{ fontSize:14.5, color:"var(--tr-fg-2)", lineHeight:1.5 }}>
                We summarised this from <strong style={{ color:"var(--tr-ink)" }}>{d.verifyBody || d.body}</strong>'s official qualification page.
              </div>
            </div>
            <a href={d.verifyUrl ? "https://" + d.verifyUrl : "#"} style={{ display:"inline-flex", alignItems:"center", gap:7, padding:"10px 16px", background:"var(--tr-brand-500)", color:"#fff", borderRadius:9, fontSize:13.5, fontWeight:600, textDecoration:"none", whiteSpace:"nowrap", flexShrink:0 }}>
              See it on {d.verifyBody || d.body} <Icon name="arrow-up-right" size={13} style={{ color:"#fff" }}/>
            </a>
          </div>
        </div>
      </div>

    </main>
  );
}

window.CourseDetail = CourseDetail;
