import { NODES, PILLARS, START_NODE, JURISDICTIONS, applyJurisdiction } from "./tree.js";

const { useState, useMemo, useEffect, useCallback } = React;
const h = React.createElement;

/* ---------- tiny inline icons (stroke, currentColor) ---------- */
const Icon = ({ d, size = 20, fill = "none", sw = 1.7, vb = 24 }) =>
  h("svg", { width: size, height: size, viewBox: `0 0 ${vb} ${vb}`, fill,
    stroke: "currentColor", strokeWidth: sw, strokeLinecap: "round", strokeLinejoin: "round" },
    Array.isArray(d) ? d.map((p, i) => h("path", { key: i, d: p })) : h("path", { d }));

const I = {
  scale: () => h("svg",{width:26,height:26,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:1.6,strokeLinecap:"round",strokeLinejoin:"round"},
    h("path",{d:"M12 3v18"}), h("path",{d:"M7 7h10"}), h("path",{d:"M7 7l-3.2 6.4a3.2 3.2 0 0 0 6.4 0L7 7z"}),
    h("path",{d:"M17 7l-3.2 6.4a3.2 3.2 0 0 0 6.4 0L17 7z"}), h("path",{d:"M8 21h8"})),
  sun: () => h(Icon,{d:["M12 2v2","M12 20v2","M4.9 4.9l1.4 1.4","M17.7 17.7l1.4 1.4","M2 12h2","M20 12h2","M4.9 19.1l1.4-1.4","M17.7 6.3l1.4-1.4"]},h("circle",{cx:12,cy:12,r:4})),
  moon: () => h(Icon,{d:"M21 12.8A9 9 0 1 1 11.2 3 7 7 0 0 0 21 12.8z"}),
  arrow: () => h(Icon,{size:18,d:["M5 12h14","M13 6l6 6-6 6"]}),
  back: () => h(Icon,{size:18,d:["M19 12H5","M11 18l-6-6 6-6"]}),
  settings: () => h(Icon,{size:18,d:["M3 6h18","M3 12h18","M3 18h18"]},h("circle",{cx:8,cy:6,r:2,fill:"var(--color-surface)"}),h("circle",{cx:16,cy:12,r:2,fill:"var(--color-surface)"}),h("circle",{cx:8,cy:18,r:2,fill:"var(--color-surface)"})),
  chevron: () => h(Icon,{size:16,d:["M6 9l6 6 6-6"]}),
  scales2: () => h(Icon,{size:18,d:["M12 3v18","M7 21h10"]}),
  restart: () => h(Icon,{size:18,d:["M3 12a9 9 0 1 0 3-6.7"]},h("path",{d:"M3 4v4h4"})),
  print: () => h(Icon,{size:18,d:["M6 9V3h12v6","M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2"]},h("rect",{x:6,y:14,width:12,height:8,rx:1})),
  seal: () => h("svg",{width:30,height:30,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:1.5,strokeLinecap:"round",strokeLinejoin:"round"},
    h("circle",{cx:12,cy:9,r:6}), h("path",{d:"M9 14.5L8 22l4-2 4 2-1-7.5"}), h("path",{d:"M9.5 9l1.7 1.7L15 7"})),
  path: () => h(Icon,{size:18,d:["M6 3v12","M18 9v12"]},h("circle",{cx:6,cy:18,r:3}),h("circle",{cx:18,cy:6,r:3}),h("path",{d:"M9 18h6a3 3 0 0 0 3-3"})),
  gavel: () => h(Icon,{size:18,d:["M14 13l-7.8 7.8a2 2 0 0 1-2.8-2.8L11.2 10","M9 7l8 8","M13 3l8 8","M16 16l5 5"]}),
  cite: () => h(Icon,{size:18,d:["M4 19.5A2.5 2.5 0 0 1 6.5 17H20","M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z"]}),
  flagIc: () => h(Icon,{size:14,d:["M4 15s1-1 4-1 5 2 8 2 4-1 4-1V3s-1 1-4 1-5-2-8-2-4 1-4 1z","M4 22v-7"]}),
  watch: () => h(Icon,{size:18,d:["M10.3 3.9 1.8 18a2 2 0 0 0 1.7 3h17a2 2 0 0 0 1.7-3L13.7 3.9a2 2 0 0 0-3.4 0z","M12 9v4","M12 17h.01"]}),
  pin: () => h(Icon,{size:13,d:"M12 21s-6-5.2-6-10a6 6 0 0 1 12 0c0 4.8-6 10-6 10z"},h("circle",{cx:12,cy:11,r:2})),
  dot: () => h(Icon,{size:13,d:"M5 12h.01M12 12h.01M19 12h.01"}),
  close: () => h(Icon,{size:20,d:["M18 6L6 18","M6 6l12 12"]}),
};

/* ---------- ordered pillar list for the rail ---------- */
const PILLAR_ORDER = ["classify", "perfect", "restrict", "govdocs", "sale"];

/* ---------- Firm identification (NY RPC 7.1(h)) ---------- */
const FIRM = {
  name: "SP Legal Advisors PLLC",
  tagline: "Counselors at Law · Est. 2020",
  address: "320 Old Country Road, Suite 103, Garden City, NY 11530",
  phones: ["(929) 244-0742", "(970) 710-1728"],
  email: "advisors@sp-firm.com",
  web: "sp-firm.com",
};
const EFFECTIVE = "June 10, 2026";

/* ---------- Legal policy content ---------- */
const LEGAL_DOCS = {
  disclaimer: {
    title: "Legal Disclaimer",
    body: [
      { p: "This page applies to the Pledged-Equity Enforcement Planner (the \u201cTool\u201d), an educational application made available by SP Legal Advisors PLLC (the \u201cFirm\u201d). By using the Tool you accept this Disclaimer in full." },
      { h: "Attorney advertising" },
      { p: "This Tool and its contents may constitute attorney advertising under the New York Rules of Professional Conduct and the rules of other jurisdictions. It is labeled \u201cAttorney Advertising\u201d for that reason. The material is provided for general informational and educational purposes and to permit you to learn more about the Firm and its work." },
      { h: "No legal advice" },
      { p: "The Tool provides general legal information about UCC Article 9 enforcement concepts. It does not provide legal advice and does not constitute a legal opinion. The information is general in nature, may not reflect the most current legal developments, and may not apply to your particular facts, collateral, governing documents, or jurisdiction. You should not act, or refrain from acting, on the basis of anything generated by the Tool without first obtaining advice from a lawyer licensed in the relevant jurisdiction." },
      { h: "No attorney-client relationship" },
      { p: "Your access to or use of the Tool does not create, and is not intended to create, an attorney-client relationship between you and the Firm or any of its attorneys. You will become a client of the Firm only if and when you and the Firm sign a written engagement agreement defining the scope of the representation." },
      { h: "No confidential or privileged communication" },
      { p: "Do not send the Firm confidential or sensitive information through the Tool or by unsolicited email. Until an attorney-client relationship is established in writing, any information you transmit is not privileged or confidential, and the Firm cannot assure that it will be treated as such or be free of conflicts." },
      { h: "Jurisdiction and unauthorized practice" },
      { p: "The Firm\u2019s attorneys are licensed to practice in the State of New York. The Tool is jurisdiction-neutral and references the uniform UCC and, where indicated, Delaware overlays; individual states adopt non-uniform variations of Article 9 and have distinct LLC, partnership, and procedural law. Nothing in the Tool is intended as a solicitation for, or the provision of, legal services in any jurisdiction where doing so would constitute the unauthorized practice of law or otherwise violate that jurisdiction\u2019s rules. The Firm does not seek to represent anyone based solely on use of the Tool." },
      { h: "No guarantee of outcome" },
      { p: "Prior results do not guarantee a similar outcome. Any description of process, remedy, or authority is illustrative only and is not a prediction or warranty about any matter." },
      { h: "No warranty; limitation of liability" },
      { p: "The Tool is provided \u201cas is\u201d and \u201cas available,\u201d without warranties of any kind, express or implied, including accuracy, completeness, currency, merchantability, or fitness for a particular purpose. To the fullest extent permitted by law, the Firm disclaims all liability for any loss or damage arising from use of, or reliance on, the Tool." },
      { p: "Questions about this Disclaimer may be directed to SP Legal Advisors PLLC, 320 Old Country Road, Suite 103, Garden City, NY 11530; (929) 244-0742; advisors@sp-firm.com." },
    ],
  },
  terms: {
    title: "Terms of Use",
    body: [
      { p: "These Terms of Use (\u201cTerms\u201d) govern your access to and use of the Pledged-Equity Enforcement Planner (the \u201cTool\u201d) provided by SP Legal Advisors PLLC (\u201cwe,\u201d \u201cus,\u201d or the \u201cFirm\u201d). By using the Tool, you agree to these Terms. If you do not agree, do not use the Tool." },
      { h: "1. Educational purpose only" },
      { p: "The Tool is an educational resource that models common UCC Article 9 enforcement issues. It does not provide legal advice, does not create an attorney-client relationship, and is not a substitute for advice from a licensed attorney. See our Legal Disclaimer, which is incorporated into these Terms." },
      { h: "2. No reliance" },
      { p: "You agree that you will not rely on the Tool as legal advice and that you will independently verify all facts, governing documents, statutes, and authorities, and consult qualified counsel, before taking or refraining from any action." },
      { h: "3. Acceptable use" },
      { list: [
        "Use the Tool only for lawful, informational purposes.",
        "Do not submit confidential, privileged, or sensitive information through the Tool.",
        "Do not attempt to disrupt, reverse engineer, scrape, or gain unauthorized access to the Tool or its underlying systems.",
        "Do not represent that your use of the Tool establishes a professional relationship with the Firm.",
      ] },
      { h: "4. Intellectual property" },
      { p: "The Tool, including its text, design, logos, decision-tree logic, and other content, is owned by or licensed to the Firm and is protected by applicable intellectual-property laws. The Firm grants you a limited, revocable, non-exclusive license to use the Tool for your own informational purposes. All other rights are reserved. \u201cSP Legal Advisors PLLC\u201d and the Firm\u2019s logo are marks of the Firm." },
      { h: "5. Disclaimer of warranties" },
      { p: "The Tool is provided \u201cas is\u201d and \u201cas available\u201d without warranty of any kind. The Firm does not warrant that the Tool will be accurate, complete, current, uninterrupted, or error-free." },
      { h: "6. Limitation of liability" },
      { p: "To the fullest extent permitted by law, the Firm and its attorneys and personnel will not be liable for any indirect, incidental, consequential, special, or punitive damages, or for any loss arising from your use of or inability to use the Tool, even if advised of the possibility of such damages." },
      { h: "7. Indemnification" },
      { p: "You agree to indemnify and hold harmless the Firm from any claims arising out of your misuse of the Tool or your breach of these Terms." },
      { h: "8. Governing law" },
      { p: "These Terms are governed by the laws of the State of New York, without regard to its conflict-of-laws rules. Any dispute relating to the Tool will be subject to the exclusive jurisdiction of the state and federal courts located in New York." },
      { h: "9. Changes" },
      { p: "We may modify these Terms or the Tool at any time. Continued use after changes become effective constitutes acceptance of the revised Terms." },
      { h: "10. Contact" },
      { p: "SP Legal Advisors PLLC, 320 Old Country Road, Suite 103, Garden City, NY 11530; (929) 244-0742 / (970) 710-1728; advisors@sp-firm.com." },
    ],
  },
  privacy: {
    title: "Privacy Policy",
    body: [
      { p: "This Privacy Policy explains how the Pledged-Equity Enforcement Planner (the \u201cTool\u201d), provided by SP Legal Advisors PLLC (the \u201cFirm\u201d), handles information." },
      { h: "Summary" },
      { p: "The Tool is designed to be privacy-protective. It runs entirely in your web browser. It does not require an account, does not use tracking or analytics, and does not transmit the information you enter to the Firm or to any server. Any matter name, date, or notes you type stay in your browser\u2019s memory for the current session only and are discarded when you close or reload the page." },
      { h: "Information we do not collect" },
      { list: [
        "We do not collect names, contact details, or account credentials through the Tool.",
        "We do not store the matter facts, notes, or selections you enter \u2014 they remain in your browser session and are never sent to us.",
        "We do not use cookies, local storage, web beacons, advertising trackers, or third-party analytics within the Tool.",
      ] },
      { h: "Information that may be processed by our host" },
      { p: "The Tool is delivered as static files by a hosting provider. As with any website, the host may automatically log basic technical request data (such as IP address, browser type, and timestamp) for security and operational purposes. The Firm does not use this data to identify you and does not combine it with any information you enter into the Tool." },
      { h: "If you contact us" },
      { p: "If you choose to email the Firm using the address shown in the Tool, we will receive the information you send (such as your email address and message). We use that information only to respond to you. Please do not send confidential or sensitive information until an attorney-client relationship has been established in writing." },
      { h: "Children" },
      { p: "The Tool is intended for adults and is not directed to children under 13. We do not knowingly collect information from children." },
      { h: "Your choices and rights" },
      { p: "Because the Tool does not collect or store personal information, there is generally no personal data for us to access, correct, or delete. If you have emailed us and wish to have that correspondence addressed, contact us at the address below." },
      { h: "Changes" },
      { p: "We may update this Privacy Policy from time to time. The \u201cEffective\u201d date above reflects the latest version." },
      { h: "Contact" },
      { p: "SP Legal Advisors PLLC, 320 Old Country Road, Suite 103, Garden City, NY 11530; (929) 244-0742; advisors@sp-firm.com." },
    ],
  },
  cookies: {
    title: "Cookie Policy",
    body: [
      { p: "This Cookie Policy describes the use of cookies and similar technologies in the Pledged-Equity Enforcement Planner (the \u201cTool\u201d) provided by SP Legal Advisors PLLC." },
      { h: "We do not use cookies" },
      { p: "The Tool does not set or read cookies. It does not use local storage, session storage, web beacons, pixels, fingerprinting, advertising trackers, or third-party analytics. No tracking technology is used to identify you or to follow your activity across sites." },
      { h: "Session data stays in your browser" },
      { p: "Any information you enter (such as a matter name, date, or notes) is held only in the page\u2019s temporary memory for your current session and is not persisted to your device or transmitted to us. Closing or reloading the page clears it." },
      { h: "Hosting" },
      { p: "The Tool is served as static files. The hosting provider may process basic, non-cookie technical request data (such as IP address) for security and delivery, as described in our Privacy Policy." },
      { h: "Changes" },
      { p: "If we introduce cookies or similar technologies in the future, we will update this policy and, where required, request your consent." },
      { h: "Contact" },
      { p: "SP Legal Advisors PLLC, 320 Old Country Road, Suite 103, Garden City, NY 11530; (929) 244-0742; advisors@sp-firm.com." },
    ],
  },
};

function App() {
  // NY RPC compliance gate — user must acknowledge before using the tool.
  // Acknowledgment lives in React state only (per-session); no storage/cookies.
  const [accepted, setAccepted] = useState(false);
  const [legalPage, setLegalPage] = useState(null);  // 'disclaimer' | 'terms' | 'privacy' | 'cookies' | null

  const [path, setPath] = useState([START_NODE]);   // node ids visited
  const [choices, setChoices] = useState([]);        // {nodeId, prompt, label, pillar} per step

  // --- Fact-pattern header + jurisdiction + scenario notes (React state only) ---
  const [jurisdiction, setJurisdiction] = useState("uniform");
  const [matterName, setMatterName] = useState("");
  const [matterDate, setMatterDate] = useState("");
  const [notes, setNotes] = useState("");
  const [setupOpen, setSetupOpen] = useState(false);

  const rawCurrent = NODES[path[path.length - 1]];
  const current = useMemo(() => applyJurisdiction(rawCurrent, jurisdiction), [rawCurrent, jurisdiction]);

  const choose = useCallback((node, opt) => {
    setChoices(c => [...c, { nodeId: node.id, prompt: node.prompt, label: opt.label, pillar: node.pillar }]);
    setPath(p => [...p, opt.next]);
    window.scrollTo({ top: 0, behavior: "smooth" });
  }, []);

  const back = useCallback(() => {
    if (path.length <= 1) return;
    setPath(p => p.slice(0, -1));
    setChoices(c => c.slice(0, -1));
    window.scrollTo({ top: 0, behavior: "smooth" });
  }, [path.length]);

  const restart = useCallback(() => { setPath([START_NODE]); setChoices([]); window.scrollTo({top:0}); }, []);

  // which pillars are touched so far / active
  const reachedPillars = useMemo(() => {
    const set = new Set(path.map(id => NODES[id].pillar));
    return set;
  }, [path]);

  const jurMeta = JURISDICTIONS[jurisdiction] || JURISDICTIONS.uniform;
  const isOutcome = current.type === "outcome";
  const isTerminal = isOutcome && current.next === null;   // final remedy
  const isInterim = isOutcome && current.next !== null;    // checkpoint finding, continues

  // Advancing past an interim finding records it as a step and moves to its `next`.
  const advance = useCallback((node) => {
    setChoices(c => [...c, { nodeId: node.id, prompt: node.title, label: (node.flags && node.flags[0]) ? node.flags[0] : node.title, pillar: node.pillar, interim: true }]);
    setPath(p => [...p, node.next]);
    window.scrollTo({ top: 0, behavior: "smooth" });
  }, []);

  return h("div", { className: "app" },
    // Compliance acknowledgment gate (NY RPC) — blocks the tool until accepted.
    !accepted && h(SplashGate, { onAccept: () => setAccepted(true), onOpenLegal: setLegalPage }),
    // Legal policy overlay (Disclaimer / Terms / Privacy / Cookies)
    legalPage && h(LegalModal, { page: legalPage, onClose: () => setLegalPage(null) }),

    h(TopBar, { onRestart: restart, jurShort: jurMeta.short, setupOpen, onToggleSetup: () => setSetupOpen(o => !o) }),
    h("div", { className: "layout screen-only" },
      h(Rail, { activePillar: current.pillar, reached: reachedPillars, choices }),
      h("main", { className: "panel" },
        h(SetupPanel, {
          open: setupOpen, onClose: () => setSetupOpen(false),
          jurisdiction, setJurisdiction,
          matterName, setMatterName, matterDate, setMatterDate,
          notes, setNotes,
        }),
        isOutcome
          ? h(Outcome, { node: current, interim: isInterim, onAdvance: advance, onBack: back, onRestart: restart, canBack: path.length > 1 })
          : h(Question, { node: current, count: choices.length, onChoose: choose, onBack: back, canBack: path.length > 1 })
      )
    ),
    isTerminal && h(PrintDoc, { node: current, choices, matterName, matterDate, notes, jurMeta }),
    h(Disclaimer, { jurMeta, onOpenLegal: setLegalPage })
  );
}

/* ---------- Compliance acknowledgment gate (NY RPC 7.1(f), 7.1(h), no-ACR/no-advice) ---------- */
function SplashGate({ onAccept, onOpenLegal }) {
  const [agree, setAgree] = useState(false);
  useEffect(() => {
    const prev = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    return () => { document.body.style.overflow = prev; };
  }, []);
  return h("div", { className: "gate screen-only", role: "dialog", "aria-modal": "true", "aria-labelledby": "gate-title" },
    h("div", { className: "gate-card" },
      h("div", { className: "gate-adlabel" }, "Attorney Advertising"),
      h("div", { className: "gate-brand" },
        h("span", { className: "gate-logo logo-wrap" },
          h("img", { className: "logo-img logo-light", src: "./brand/sp-mark.png", alt: FIRM.name }),
          h("img", { className: "logo-img logo-dark", src: "./brand/sp-mark-inverse.png", alt: "", "aria-hidden": "true" })),
        h("div", null,
          h("div", { className: "gate-firm" }, FIRM.name),
          h("div", { className: "gate-tag" }, FIRM.tagline))),

      h("h1", { id: "gate-title", className: "gate-title" }, "Before you continue"),
      h("p", { className: "gate-lead" },
        "The Pledged-Equity Enforcement Planner is a free educational tool that models common UCC Article\u00a09 enforcement issues. Please read and acknowledge the following before using it."),

      h("ul", { className: "gate-points" },
        h("li", null, h("strong", null, "No legal advice. "),
          "This tool provides general legal information only. It is not legal advice, is not a legal opinion, and may not reflect the most current law. Outputs are general and may not apply to your specific facts or jurisdiction."),
        h("li", null, h("strong", null, "No attorney-client relationship. "),
          "Using this tool does not create an attorney-client relationship between you and " + FIRM.name + ". You become a client only through a signed engagement agreement."),
        h("li", null, h("strong", null, "Do not send confidential information. "),
          "Do not submit confidential or time-sensitive information through this tool. Communications made here are not privileged and will not be treated as confidential."),
        h("li", null, h("strong", null, "Consult a licensed attorney. "),
          "Laws vary by jurisdiction and change over time. Consult a lawyer licensed in the relevant jurisdiction before acting. Prior results do not guarantee a similar outcome.")),

      h("div", { className: "gate-firmbox" },
        h("div", { className: "gate-firmbox-l" }, "Attorney responsible for this content"),
        h("div", { className: "gate-firmbox-b" },
          h("strong", null, FIRM.name), h("br"),
          FIRM.address, h("br"),
          FIRM.phones.join(" \u00b7 "), h("br"),
          h("a", { href: "mailto:" + FIRM.email }, FIRM.email))),

      h("label", { className: "gate-check" },
        h("input", { type: "checkbox", checked: agree, onChange: e => setAgree(e.target.checked) }),
        h("span", null, "I have read and understand the above. I acknowledge this tool does not provide legal advice and does not create an attorney-client relationship.")),

      h("button", { className: "gate-btn", disabled: !agree, onClick: onAccept }, "Enter the planner"),

      h("div", { className: "gate-links" },
        h("button", { className: "linklike", onClick: () => onOpenLegal("disclaimer") }, "Full Disclaimer"),
        h("button", { className: "linklike", onClick: () => onOpenLegal("terms") }, "Terms of Use"),
        h("button", { className: "linklike", onClick: () => onOpenLegal("privacy") }, "Privacy Policy"),
        h("button", { className: "linklike", onClick: () => onOpenLegal("cookies") }, "Cookie Policy"))
    )
  );
}

/* ---------- Top bar ---------- */
function TopBar({ onRestart, jurShort, setupOpen, onToggleSetup }) {
  const toggle = () => {
    const r = document.documentElement;
    const cur = r.getAttribute("data-theme") ||
      (matchMedia("(prefers-color-scheme:dark)").matches ? "dark" : "light");
    r.setAttribute("data-theme", cur === "dark" ? "light" : "dark");
    setDark(cur !== "dark");
  };
  const [dark, setDark] = useState(matchMedia("(prefers-color-scheme:dark)").matches);
  return h("header", { className: "topbar screen-only" },
    h("div", { className: "brand" },
      h("span", { className: "mark logo-wrap" },
        h("img", { className: "logo-img logo-light", src: "./brand/sp-mark.png", alt: "SP Legal Advisors PLLC" }),
        h("img", { className: "logo-img logo-dark", src: "./brand/sp-mark-inverse.png", alt: "", "aria-hidden": "true" })),
      h("div", { className: "titles" },
        h("span", { className: "t0" }, "SP Legal Advisors PLLC"),
        h("span", { className: "t1" }, "Pledged-Equity Enforcement Planner"),
        h("span", { className: "t2" }, "Article 9 remedy decision tree"))),
    h("span", { className: "spacer" }),
    h("button", { className: `setupbtn ${setupOpen ? "on" : ""}`, onClick: onToggleSetup, "aria-expanded": setupOpen, title: "Matter details, jurisdiction & notes" },
      h(I.settings),
      h("span", { className: "setupbtn-lbl" }, "Matter setup"),
      h("span", { className: "jur-badge" }, jurShort)),
    h("button", { className: "iconbtn", onClick: onRestart, "aria-label": "Start over", title: "Start over" }, h(I.restart)),
    h("button", { className: "iconbtn", onClick: toggle, "aria-label": "Toggle theme", title: "Toggle light / dark" }, dark ? h(I.sun) : h(I.moon))
  );
}

/* ---------- Setup panel: fact-pattern header + jurisdiction + notes ---------- */
function SetupPanel({ open, onClose, jurisdiction, setJurisdiction, matterName, setMatterName, matterDate, setMatterDate, notes, setNotes }) {
  if (!open) return null;
  return h("section", { className: "setup fade" },
    h("div", { className: "setup-head" },
      h("h2", null, "Matter setup"),
      h("button", { className: "setup-close", onClick: onClose, "aria-label": "Close setup" }, h(I.chevron))),
    h("p", { className: "setup-note" }, "These details label your printed planning memo. Nothing is saved or transmitted — they live only in this browser session."),

    h("div", { className: "setup-grid" },
      h("label", { className: "fld" },
        h("span", { className: "fld-l" }, "Matter / fact-pattern name"),
        h("input", { type: "text", value: matterName, placeholder: "e.g. Acme Holdings LLC — Member pledge enforcement",
          onChange: e => setMatterName(e.target.value) })),
      h("label", { className: "fld fld-date" },
        h("span", { className: "fld-l" }, "Date"),
        h("input", { type: "date", value: matterDate, onChange: e => setMatterDate(e.target.value) }))),

    h("div", { className: "fld" },
      h("span", { className: "fld-l" }, "Jurisdiction"),
      h("div", { className: "jur-seg", role: "radiogroup", "aria-label": "Jurisdiction" },
        Object.values(JURISDICTIONS).map(j =>
          h("button", { key: j.id, role: "radio", "aria-checked": jurisdiction === j.id,
            className: `jur-opt ${jurisdiction === j.id ? "on" : ""}`,
            onClick: () => setJurisdiction(j.id) },
            h("span", { className: "jur-opt-l" }, j.label)))),
      h("p", { className: "jur-blurb" }, (JURISDICTIONS[jurisdiction] || JURISDICTIONS.uniform).blurb)),

    h("label", { className: "fld" },
      h("span", { className: "fld-l" }, "Scenario notes"),
      h("textarea", { value: notes, rows: 4,
        placeholder: "Optional. Key facts, open questions, or assumptions to carry into the memo (e.g. certificate location, agreement provisions reviewed, counterparties).",
        onChange: e => setNotes(e.target.value) }))
  );
}

/* ---------- Progress rail ---------- */
function Rail({ activePillar, reached, choices }) {
  const answersByPillar = {};
  choices.forEach(c => { (answersByPillar[c.pillar] ||= []).push(c.label); });
  const activeIdx = PILLAR_ORDER.indexOf(activePillar);
  return h("aside", { className: "rail" },
    h("h2", null, "Analysis path"),
    h("ol", { className: "steps" },
      PILLAR_ORDER.map((pid, i) => {
        const done = i < activeIdx;
        const active = pid === activePillar;
        const ans = answersByPillar[pid];
        return h("li", { key: pid, className: `step ${done ? "done" : ""} ${active ? "active" : ""}` },
          h("span", { className: "dot" }, done ? "✓" : i + 1),
          h("span", { className: "lbl" },
            h("span", { className: "nm" }, PILLARS[pid].short),
            ans && ans.length ? h("span", { className: "ans" }, ans[ans.length - 1]) : null));
      }))
  );
}

/* ---------- Question view ---------- */
function Question({ node, count, onChoose, onBack, canBack }) {
  return h("section", { className: "question-view fade", key: node.id },
    h("span", { className: "pillar-tag" }, PILLARS[node.pillar].label),
    h("div", { className: "qcount" }, `Decision ${count + 1}`),
    h("h1", { className: "question" }, node.prompt),
    node.help && h("p", { className: "help" }, node.help),
    node.deHelpNote ? h("div", { className: "de-callout" },
      h("span", { className: "de-tag" }, h(I.scales2), "Delaware"),
      h("p", null, node.deHelpNote)) : null,
    h("div", { className: "options", role: "group", "aria-label": node.prompt },
      node.options.map((opt, i) =>
        h("button", { key: i, className: "option", onClick: () => onChoose(node, opt) },
          h("span", { className: "marker" }, h(I.arrow)),
          h("span", { className: "otext" },
            h("span", { className: "olabel" }, opt.label),
            opt.sub && h("span", { className: "osub" }, opt.sub))))),
    h("div", { className: "actions" },
      h("button", { className: "btn", onClick: onBack, disabled: !canBack }, h(I.back), "Back"))
  );
}

/* ---------- Outcome view ---------- */
function CiteItem({ text }) {
  // Bold the statutory token(s) (e.g. "UCC § 9-610(a)-(b)" or "UCC § 9-615 / § 9-616"),
  // leaving the trailing parenthetical description in normal weight.
  // The description always begins at the first " (" that is preceded by whitespace.
  const m = text.match(/^(.*?)(\s+\([^)]*\).*)$/);
  if (m) return h("li", null, h("span", { className: "pin" }, h(I.pin)),
    h("span", null, h("span", { className: "sec" }, m[1].trim()), " ", m[2].trim()));
  return h("li", null, h("span", { className: "pin" }, h(I.pin)), h("span", null, text));
}

function Outcome({ node, interim, onAdvance, onBack, onRestart, canBack }) {
  const meansLabel = interim ? "Finding" : "What this means";
  const remedyLabel = interim ? "Implication for the analysis" : "Recommended remedy / next step";
  return h("section", { className: "outcome fade", key: node.id },
    h("div", { className: "outcome-sub" }, `${PILLARS[node.pillar].label} · ${interim ? "Interim finding" : "Recommended path"}`),
    h("div", { className: "outcome-head" },
      h("span", { className: "seal" }, h(I.seal)),
      h("h1", { className: "outcome-title" }, node.title)),
    node.flags && node.flags.length ? h("div", { className: "flags" },
      node.flags.map((f, i) => h("span", { key: i, className: "flag" }, h(I.flagIc), " ", f))) : null,

    h("div", { className: "ocard" },
      h("div", { className: "ohead" }, h("span", { className: "ic" }, h(I.path)), h("h3", null, meansLabel)),
      h("div", { className: "obody" }, h("p", null, node.summary))),

    h("div", { className: "ocard" },
      h("div", { className: "ohead" }, h("span", { className: "ic" }, h(I.gavel)), h("h3", null, remedyLabel)),
      h("div", { className: "obody" }, h("p", null, node.remedy))),

    node.deNote ? h("div", { className: "ocard de-card" },
      h("div", { className: "ohead" }, h("span", { className: "ic" }, h(I.scales2)), h("h3", null, "Delaware overlay")),
      h("div", { className: "obody" }, h("p", null, node.deNote))) : null,

    h("div", { className: "ocard" },
      h("div", { className: "ohead" }, h("span", { className: "ic" }, h(I.cite)), h("h3", null, node.deNote ? "Key authority (UCC + Delaware)" : "Key UCC authority")),
      h("div", { className: "obody" }, h("ul", { className: "cites" }, node.cites.map((c, i) => h(CiteItem, { key: i, text: c }))))),

    node.watchpoints && node.watchpoints.length ? h("div", { className: "ocard" },
      h("div", { className: "ohead" }, h("span", { className: "ic" }, h(I.watch)), h("h3", null, "Watch-points")),
      h("div", { className: "obody" }, h("ul", { className: "watch" },
        node.watchpoints.map((w, i) => h("li", { key: i }, h("span",{className:"wm"},h(I.dot)), h("span", null, w)))))) : null,

    h("div", { className: "actions" },
      interim
        ? h("button", { className: "btn primary", onClick: () => onAdvance(node) }, "Continue", h(I.arrow))
        : h("button", { className: "btn primary", onClick: () => window.print() }, h(I.print), "Print summary"),
      h("button", { className: "btn", onClick: onBack, disabled: !canBack }, h(I.back), "Back"),
      h("button", { className: "btn", onClick: onRestart }, h(I.restart), "New scenario"))
  );
}

/* ---------- Printable memo ---------- */
function PrintDoc({ node, choices, matterName, matterDate, notes, jurMeta }) {
  const now = new Date();
  const stamp = now.toLocaleString("en-US", { year:"numeric", month:"long", day:"numeric", hour:"2-digit", minute:"2-digit" });
  const matterDateFmt = matterDate
    ? new Date(matterDate + "T00:00:00").toLocaleDateString("en-US", { year:"numeric", month:"long", day:"numeric" })
    : "";
  const title = (matterName && matterName.trim()) ? matterName.trim() : "Pledged-Equity Enforcement — Planning Summary";
  const metaBits = ["Internal planning memo"];
  metaBits.push(`Jurisdiction: ${jurMeta ? jurMeta.label : "Uniform UCC"}`);
  if (matterDateFmt) metaBits.push(`Matter date: ${matterDateFmt}`);
  metaBits.push(`Generated ${stamp}`);
  return h("div", { className: "print-only print-doc" },
    h("div", { className: "plet" },
      h("img", { className: "plet-mark", src: "./brand/sp-mark.png", alt: "" }),
      h("div", { className: "plet-txt" },
        h("div", { className: "plet-firm" }, "SP Legal Advisors PLLC"),
        h("div", { className: "plet-sub" }, "Counselors at Law · Est. 2020"))),
    h("div", { className: "ph" },
      h("div", { className: "pt" }, title),
      matterName && matterName.trim() ? h("div", { className: "psub" }, "Pledged-Equity Enforcement — Planning Summary") : null,
      h("div", { className: "pmeta" }, metaBits.join(" · "))),

    notes && notes.trim() ? h(React.Fragment, null,
      h("h2", null, "Scenario notes"),
      h("p", { className: "pnotes" }, notes.trim())) : null,

    h("h2", null, "Fact pattern (path taken)"),
    h("ul", { className: "pathlist" },
      choices.map((c, i) => h("li", { key: i },
        h("span", { className: "pq" }, c.prompt),
        h("span", { className: "pa" }, c.label)))),

    h("h2", null, "Recommended path"),
    h("p", null, h("strong", null, node.title)),

    node.flags && node.flags.length ? h("div", { className: "pflags" },
      node.flags.map((f, i) => h("span", { key: i }, f))) : null,

    h("h2", null, "What this means"),
    h("p", null, node.summary),

    node.deNote ? h(React.Fragment, null,
      h("h2", null, "Delaware overlay"),
      h("p", null, node.deNote)) : null,

    h("h2", null, "Recommended remedy / next step"),
    h("p", null, node.remedy),

    h("h2", null, node.deNote ? "Key authority (UCC + Delaware)" : "Key UCC authority"),
    h("ul", { className: "pcites" }, node.cites.map((c, i) => h("li", { key: i }, c.replace(/^UCC\s+§*\s*/, "§ ")))),

    node.watchpoints && node.watchpoints.length ? h(React.Fragment, null,
      h("h2", null, "Watch-points"),
      h("ul", { className: "pwatch" }, node.watchpoints.map((w, i) => h("li", { key: i }, w)))) : null,

    h("div", { className: "pfoot" },
      h("p", { className: "pfoot-disc" },
        jurMeta && jurMeta.id === "de"
          ? "This summary is an educational planning aid generated from a decision-tree model of UCC Article 9, transfer-restriction, governing-document, and sale-mechanics issues, with Delaware LLC Act (6 Del. C. ch. 18) and LP Act (ch. 17) overlays applied. Delaware has adopted Article 9 substantially uniform; confirm the controlling agreement provisions and any non-uniform enactments. It is general legal information only \u2014 not legal advice and not a legal opinion \u2014 and does not create an attorney-client relationship. Confirm all facts and authorities and consult a licensed attorney before acting. Prior results do not guarantee a similar outcome."
          : "This summary is an educational planning aid generated from a decision-tree model of UCC Article 9, transfer-restriction, governing-document, and sale-mechanics issues. It is jurisdiction-neutral and references the uniform UCC; confirm the controlling state's enactment and any non-uniform provisions. It is general legal information only \u2014 not legal advice and not a legal opinion \u2014 and does not create an attorney-client relationship. Confirm all facts and authorities and consult a licensed attorney before acting. Prior results do not guarantee a similar outcome."),
      h("p", { className: "pfoot-firm" },
        "Attorney Advertising \u00b7 " + FIRM.name + " \u00b7 " + FIRM.address + " \u00b7 " + FIRM.phones.join(" / ") + " \u00b7 " + FIRM.email))
  );
}

/* ---------- Disclaimer footer (persistent; NY RPC 7.1(f) & 7.1(h)) ---------- */
function Disclaimer({ jurMeta, onOpenLegal }) {
  const de = jurMeta && jurMeta.id === "de";
  return h("footer", { className: "disclaimer screen-only" },
    h("div", { className: "disc-adlabel" }, "Attorney Advertising"),
    h("p", null,
      h("strong", null, "Educational tool \u2014 not legal advice. "),
      de
        ? "This decision tree models common Article 9 enforcement issues for pledged equity, with Delaware LLC Act (6 Del. C. ch. 18) and LP Act (ch. 17) overlays applied to the relevant findings. It is general legal information and an analytical aid only \u2014 not legal advice and not a legal opinion. Confirm the controlling agreement provisions, any non-uniform UCC enactments, the governing documents, and current facts, and consult a licensed attorney before acting."
        : "This decision tree models common Article 9 enforcement issues for pledged equity and is jurisdiction-neutral (uniform UCC). It is general legal information and an analytical aid only \u2014 not legal advice and not a legal opinion. Confirm the controlling jurisdiction, any non-uniform UCC enactments, the governing documents, and current facts, and consult a licensed attorney before acting."),
    h("p", { className: "disc-noacr" },
      "Use of this tool does not create an attorney-client relationship, and information submitted here is not confidential or privileged. Do not send confidential information. ",
      h("em", null, "Prior results do not guarantee a similar outcome."),
      " The firm does not intend this tool as a solicitation in any jurisdiction where it would not comply with that jurisdiction's rules."),
    h("div", { className: "disc-firm" },
      h("span", { className: "disc-firm-name" }, FIRM.name),
      h("span", { className: "disc-sep" }, "\u00b7"),
      h("span", null, FIRM.address),
      h("span", { className: "disc-sep" }, "\u00b7"),
      h("span", null, FIRM.phones[0]),
      h("span", { className: "disc-sep" }, "\u00b7"),
      h("a", { href: "mailto:" + FIRM.email }, FIRM.email)),
    h("div", { className: "disc-links" },
      h("button", { className: "linklike", onClick: () => onOpenLegal("disclaimer") }, "Disclaimer"),
      h("button", { className: "linklike", onClick: () => onOpenLegal("terms") }, "Terms of Use"),
      h("button", { className: "linklike", onClick: () => onOpenLegal("privacy") }, "Privacy Policy"),
      h("button", { className: "linklike", onClick: () => onOpenLegal("cookies") }, "Cookie Policy")),
    h("p", { className: "attribution" }, "\u00a9 " + new Date().getFullYear() + " " + FIRM.name + ". All rights reserved. Attorney advertising prepared by " + FIRM.name + ". " + FIRM.address + ".")
  );
}

/* ---------- Legal policy modal (Disclaimer / Terms / Privacy / Cookies) ---------- */
function LegalModal({ page, onClose }) {
  useEffect(() => {
    const prev = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    const onKey = e => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    return () => { document.body.style.overflow = prev; window.removeEventListener("keydown", onKey); };
  }, [onClose]);
  const doc = LEGAL_DOCS[page];
  return h("div", { className: "legal-overlay screen-only", role: "dialog", "aria-modal": "true", "aria-labelledby": "legal-title",
      onClick: e => { if (e.target === e.currentTarget) onClose(); } },
    h("div", { className: "legal-card" },
      h("div", { className: "legal-head" },
        h("div", null,
          h("div", { className: "legal-kicker" }, FIRM.name + " \u00b7 Attorney Advertising"),
          h("h2", { id: "legal-title", className: "legal-title" }, doc.title)),
        h("button", { className: "legal-close", onClick: onClose, "aria-label": "Close" }, h(I.close))),
      h("div", { className: "legal-body" },
        h("p", { className: "legal-eff" }, "Effective " + EFFECTIVE),
        doc.body.map((blk, i) => {
          if (blk.h) return h("h3", { key: i, className: "legal-h" }, blk.h);
          if (blk.list) return h("ul", { key: i, className: "legal-list" }, blk.list.map((it, j) => h("li", { key: j }, it)));
          return h("p", { key: i, className: "legal-p" }, blk.p);
        })),
      h("div", { className: "legal-foot" },
        h("span", null, FIRM.name + " \u00b7 " + FIRM.address + " \u00b7 " + FIRM.phones[0]),
        h("button", { className: "gate-btn legal-okbtn", onClick: onClose }, "Close"))
    )
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(h(App));
