// CTL 2025 — Concept Explainer
// Generic slide-over panel for cluster-level definitions and primers.
// Currently hosts "What is a Muqawala?"; structured so additional concepts
// can be added without expanding component surface.

(function () {
  const { createContext, useContext, useState, useCallback, useEffect, useMemo, useRef } = React;

  const ConceptCtx = createContext({ open: () => {} });
  window.useConceptPeek = () => useContext(ConceptCtx);

  // ── concept registry ─────────────────────────────────────────────────────
  // Each concept renders as a slide-over with the same chrome as the
  // article peek. Render functions receive { ArticleRef } so the body
  // can deep-link to gazetted articles.
  const CONCEPTS = {
    mudaraba: {
      eyebrow: ["Cluster 06 · Mudaraba primer", "Federal Decree-Law No. 25 of 2025"],
      title: "What is mudaraba?",
      render: ({ ArticleRef }) => (
        <>
          <p className="concept-lede">
            Mudaraba (مضاربة) is a profit-sharing contract: one party (<em>rabb al-māl</em>) provides capital, the other (<em>mudārib</em>) invests and manages it. Under the 1985 Code, mudaraba sat inside the civil-companies framework. Under the 2025 Code, it is lifted out and codified as a standalone named contract at Articles 655–670 — clarifying that it is an investment-and-profit-share relationship, not a corporate form.
          </p>

          <section className="concept-section">
            <h4 className="concept-h">Statutory definition</h4>
            <blockquote className="concept-quote">
              <q>Mudaraba is a contract under which a capital provider delivers funds to another who undertakes to invest them in return for a proportional share of the profit.</q>
              <cite><ArticleRef number={655}>Article 655</ArticleRef></cite>
            </blockquote>
            <p>
              Two parties, one capital flow, one profit-share. The capital provider (rabb al-māl) supplies funds; the mudarib supplies effort and management; the upside is split by a pre-agreed ratio.
            </p>
          </section>

          <section className="concept-section">
            <h4 className="concept-h">The fixed-return prohibition — why mudaraba is not a loan</h4>
            <blockquote className="concept-quote">
              <q>It is not permissible in the Mudaraba contract to stipulate a fixed amount of profit for one of the contracting parties.</q>
              <cite><ArticleRef number={664}>Article 664(1)</ArticleRef></cite>
            </blockquote>
            <p>
              This is the structural feature that distinguishes mudaraba from debt. A fixed profit for either party converts the relationship into something other than mudaraba — typically a loan with interest, which raises Sharia-compliance and recharacterisation issues. <ArticleRef number={664}>Article 664(2)</ArticleRef> permits a "ceiling-and-above" split (e.g. profits up to a threshold to one party, the excess to the other) — this remains a true profit-share, not a fixed return.
            </p>
          </section>

          <section className="concept-section">
            <h4 className="concept-h">Profit, loss, and the mudarib's duties</h4>
            <p>
              <strong>Profit:</strong> determined by agreement (<ArticleRef number={663}>Art. 663(1)</ArticleRef>); failing agreement, by custom or the court (<ArticleRef number={663}>Art. 663(2)</ArticleRef>). Entitlement crystallises on termination unless the parties agree to periodic valuation (<ArticleRef number={665}>Art. 665(1)</ArticleRef>).
            </p>
            <p>
              <strong>Loss:</strong> falls on the capital provider — the mudarib's contribution is effort, not capital — unless the loss is caused by the mudarib's fault or breach of the contract terms (<ArticleRef number={668}>Art. 668</ArticleRef>, <ArticleRef number={669}>Art. 669</ArticleRef>).
            </p>
            <p>
              <strong>The mudarib's duties:</strong> deliver information and account (<ArticleRef number={659}>Art. 659</ArticleRef>); observe restrictions in the contract on time, place or activity (<ArticleRef number={660}>Art. 660</ArticleRef>); no commingling of mudaraba capital with the mudarib's own funds, and no sub-delegation, absent authorisation or custom (<ArticleRef number={661}>Art. 661</ArticleRef>).
            </p>
          </section>

          <section className="concept-section">
            <h4 className="concept-h">Term and termination</h4>
            <p>
              A mudaraba may be for a fixed term or indefinite. It terminates on lapse of term or completion of the work (<ArticleRef number={666}>Art. 666</ArticleRef>); for indefinite mudarabas, either party may withdraw on reasonable notice (<ArticleRef number={667}>Art. 667</ArticleRef>). It also terminates on the death, interdiction, insolvency, or liquidation of either party (<ArticleRef number={670}>Art. 670</ArticleRef>).
            </p>
          </section>

          <section className="concept-section">
            <h4 className="concept-h">Why the carve-out matters</h4>
            <p>
              Under the old Code's placement, mudaraba inherited civil-companies rules on formation, capital contribution, partner withdrawal and dissolution — a poor fit for a profit-share investment contract. The 2025 relocation means the company-formation rules no longer apply by default; the named-contract regime at <ArticleRef number={655}>Arts. 655–670</ArticleRef> governs. In practice, the impact is sharpest on any Sharia-compliant developer financing, real-estate investment fund, or profit-share arrangement with a capital partner documented as mudaraba — those should be re-papered against the 655–670 framework, with particular attention to the <ArticleRef number={664}>fixed-return prohibition</ArticleRef>.
            </p>
          </section>
        </>
      ),
    },
    muqawala: {
      eyebrow: ["Cluster 03 · Construction primer", "Federal Decree-Law No. 25 of 2025"],
      title: "What is a muqawala?",
      render: ({ ArticleRef }) => (
        <>
          <p className="concept-lede">
            Muqawala (المقاولة) is the civil-law category that the Code's construction chapter operates on. Whether Article 829's hardship clause, Article 821's decennial liability, or Article 836's termination-for-convenience power applies turns on whether the contract is muqawala — not on what it is called.
          </p>

          <section className="concept-section">
            <h4 className="concept-h">Statutory definition</h4>
            <blockquote className="concept-quote">
              <q>A contracting agreement (Muqawala) is a contract whereby one of the contracting parties undertakes to manufacture a thing or to perform a work for a consideration to be paid by the other contracting party.</q>
              <cite><ArticleRef number={812}>Article 812</ArticleRef></cite>
            </blockquote>
            <p>
              Two elements: a <strong>work or thing to be produced</strong>, and a <strong>consideration</strong>. Independent execution (the contractor is not under the employer's day-to-day supervision in the manner of an employee) is implicit in the broader chapter structure.
            </p>
          </section>

          <section className="concept-section">
            <h4 className="concept-h">Substance prevails over label</h4>
            <p>
              Classification turns on the actual obligations, not on the contract's title. The Code's interpretation hierarchy at <ArticleRef number={119}>Article 119</ArticleRef> directs the court to give effect to the parties' real intention and the nature of the transaction; the doctrine of <em>takyīf</em> (تكييف / qualification) requires courts to classify a contract by reference to its essential elements rather than its name. This is consistent UAE Court of Cassation jurisprudence and is uncontested in firm commentary.
            </p>
            <p>
              A "Services Agreement", "EPC Contract", or "Supply &amp; Install Agreement" with muqawala substance is muqawala. A pure off-the-shelf goods supply with no manufacturing or installation component is a sale under <ArticleRef number={445}>Article 445</ArticleRef>, not muqawala.
            </p>
          </section>

          <section className="concept-section">
            <h4 className="concept-h">What falls in</h4>
            <table className="concept-table">
              <tbody>
                <tr><td>EPC / building / civil works contract</td><td className="is-yes">Muqawala</td></tr>
                <tr><td>Architecture / engineering design contract</td><td className="is-yes">Muqawala</td></tr>
                <tr><td>Consultancy with defined deliverables</td><td className="is-yes">Muqawala</td></tr>
                <tr><td>Supply &amp; install agreement</td><td className="is-yes">Muqawala (the install element brings it in)</td></tr>
                <tr><td>Made-to-measure manufacturing</td><td className="is-yes">Muqawala</td></tr>
                <tr><td>Maintenance with a defined output</td><td className="is-yes">Muqawala</td></tr>
                <tr><td>Pure off-the-shelf goods supply</td><td className="is-no">Sale (Art. 445)</td></tr>
                <tr><td>Open-ended service / management without a defined "work"</td><td className="is-borderline">Borderline — depends on result-deliverable</td></tr>
                <tr><td>Mixed sale + muqawala (e.g. equipment + commissioning)</td><td className="is-borderline">Predominant-element test, or dissected</td></tr>
              </tbody>
            </table>
          </section>

          <section className="concept-section">
            <h4 className="concept-h">Why this matters in Cluster 03</h4>
            <p>
              Every card in this cluster — termination for convenience (<ArticleRef number={836}>Art. 836</ArticleRef>), risk allocation on delivery (<ArticleRef number={837}>Art. 837</ArticleRef>), lump-sum hardship (<ArticleRef number={829}>Art. 829</ArticleRef>), the contractor's statutory notice duty (<ArticleRef number={816}>Art. 816(3)</ArticleRef>), and the subcontractor terminology change (<ArticleRef number={832}>Art. 832</ArticleRef>) — sits inside the muqawala chapter. Each reaches exactly as far as the muqawala qualification reaches, and no further.
            </p>
          </section>
        </>
      ),
    },
  };

  function ConceptPeekProvider({ children }) {
    const [activeId, setActiveId] = useState(null);

    const open = useCallback((id) => {
      if (!(id in CONCEPTS)) return;
      setActiveId(id);
    }, []);

    const close = useCallback(() => setActiveId(null), []);

    useEffect(() => {
      if (activeId == null) return;
      const handler = (e) => { if (e.key === 'Escape') { close(); e.preventDefault(); } };
      window.addEventListener('keydown', handler);
      return () => window.removeEventListener('keydown', handler);
    }, [activeId, close]);

    const ctx = useMemo(() => ({ open, close, activeId }), [open, close, activeId]);

    return (
      <ConceptCtx.Provider value={ctx}>
        {children}
        <ConceptPanel />
      </ConceptCtx.Provider>
    );
  }
  window.ConceptPeekProvider = ConceptPeekProvider;

  // ── ConceptTrigger — clickable affordance ────────────────────────────────
  function ConceptTrigger({ conceptId, label, className }) {
    const { open } = useContext(ConceptCtx);
    return (
      <button
        type="button"
        className={"concept-trigger " + (className || "")}
        onClick={(e) => { e.stopPropagation(); open(conceptId); }}
      >
        <span className="cq">?</span>
        <span className="cl">{label}</span>
      </button>
    );
  }
  window.ConceptTrigger = ConceptTrigger;

  // ── Panel ────────────────────────────────────────────────────────────────
  function ConceptPanel() {
    const { activeId, close } = useContext(ConceptCtx);
    const contentRef = useRef(null);
    const isOpen = activeId != null;
    const concept = isOpen ? CONCEPTS[activeId] : null;

    useEffect(() => {
      if (isOpen && contentRef.current) {
        contentRef.current.scrollTop = 0;
      }
    }, [activeId, isOpen]);

    return (
      <>
        <div
          className={"concept-scrim" + (isOpen ? " open" : "")}
          onClick={close}
          aria-hidden={!isOpen}
        ></div>
        <aside
          className={"concept-panel" + (isOpen ? " open" : "")}
          role="dialog"
          aria-modal="true"
          aria-label={concept ? concept.title : ""}
        >
          {concept && (
            <>
              <header className="concept-head">
                <div className="concept-head-top">
                  <div className="concept-eyebrow">
                    {concept.eyebrow.map((line, i) => <span key={i}>{line}</span>)}
                  </div>
                  <button className="concept-close" onClick={close} aria-label="Close">×</button>
                </div>
                <h2 className="concept-title">{concept.title}</h2>
              </header>
              <div className="concept-content" ref={contentRef}>
                {concept.render({ ArticleRef: window.ArticleRef })}
              </div>
              <footer className="concept-foot">
                <span>Article references open in the gazetted text · Esc to close</span>
              </footer>
            </>
          )}
        </aside>
      </>
    );
  }
})();
