// purchase_agreement.jsx — Purchase Agreement schema + draft template + demo values
// Source: CEG Purchase Agreement boilerplate (uploads/Purchase Agreement - CEG Boilerplate 5.14.26.docx).
// Mutates the schema/template/demo registries owned by data.jsx.

const { Filled: FilledPA } = window;

// Reuse the broker directory established in listings.jsx (loaded earlier).
const PA_BROKERS = window.__BROKERS__ || [];
const PA_BROKER_EMAIL_CASCADE = window.__BROKER_EMAIL_CASCADE__ || {};

// ─── Field-builder shorthand (local) ──────────────────────────────────
const PT  = (id, label, o={}) => ({ id, label, type: 'text', ...o });
const PTA = (id, label, o={}) => ({ id, label, type: 'textarea', ...o });
const PSF = (id, label, o={}) => ({ id, label, type: 'sf', ...o });
const PUSD = (id, label, o={}) => ({ id, label, type: 'currency', suffix: 'USD', ...o });
const PDT  = (id, label, o={}) => ({ id, label, type: 'date', ...o });
const PSEL = (id, label, options, o={}) => ({ id, label, type: 'select', options, ...o });
const PEML = (id, label, o={}) => ({ id, label, type: 'email', ...o });
const PINT = (id, label, o={}) => ({ id, label, type: 'text', placeholder: '60', ...o });

const BUYER_ENTITY_TYPES = [
  'a Minnesota limited liability company',
  'a Minnesota corporation',
  'a Minnesota limited partnership',
  'a Minnesota general partnership',
  'an individual',
  'a Delaware limited liability company',
  'a Delaware corporation',
  'Other (type into the form)',
];

const CONTINGENCY_DAY_OPTIONS = ['15', '21', '30', '45', '60', '75', '90', '120'];

// ─── Form schema ──────────────────────────────────────────────────────

const SCHEMA_PURCHASE_AGREEMENT = {
  title: 'Purchase Agreement',
  subtitle: 'Real estate purchase contract — Buyer ↔ Seller, full Minnesota commercial form',
  sections: [
    {
      id: 'property', title: 'Property', icon: 'building-2',
      fields: [
        PT('propertyAddress', 'Property address', { required: true, span: 2, placeholder: '8200 Penn Ave S' }),
        PT('propertyCity', 'City', { required: true, span: 1, placeholder: 'Bloomington' }),
        PT('propertyZip', 'ZIP', { required: true, span: 1, placeholder: '55431', help: 'State is Minnesota.' }),
        PT('propertyCounty', 'County', { required: true, span: 1, placeholder: 'Hennepin', help: 'Used for governing-law/venue clause.' }),
        PSF('propertySquareFootage', 'Square footage', { required: true, span: 1, placeholder: '14,200' }),
      ],
    },
    {
      id: 'parties', title: 'Parties', icon: 'users',
      fields: [
        PT('buyerEntity', 'Buyer entity', { required: true, span: 2, placeholder: 'Northstar Industrial Acquisitions LP', help: 'Legal entity buying the property.' }),
        PSEL('buyerEntityType', 'Buyer entity type', BUYER_ENTITY_TYPES, { required: true, span: 2, help: 'How the entity is described in the doc (e.g. "a Minnesota LLC").' }),
        PT('sellerEntity', 'Seller entity', { required: true, span: 2, placeholder: 'Penn Ave Capital LLC', help: 'Legal entity selling the property — should match the deed.' }),
        PT('sellerRepresentativeName', 'Seller representative', { required: true, span: 2, placeholder: 'Curtis Walsh', help: 'The named individual whose "knowledge" is referenced in Seller\'s representations.' }),
      ],
    },
    {
      id: 'price', title: 'Purchase Price & Earnest Money', icon: 'dollar-sign',
      fields: [
        PUSD('purchasePriceNumeric', 'Purchase price (numeric)', { required: true, span: 1, placeholder: '3,750,000' }),
        PT('purchasePriceWords', 'Purchase price (written out)', { required: true, span: 1, placeholder: 'Three Million Seven Hundred Fifty Thousand', help: 'Required in legal document — must spell out the amount.' }),
        PUSD('earnestMoneyNumeric', 'Earnest money (numeric)', { required: true, span: 1, placeholder: '75,000', help: 'Typical: 1–5% of purchase price.' }),
        PT('earnestMoneyWords', 'Earnest money (written out)', { required: true, span: 1, placeholder: 'Seventy-Five Thousand' }),
      ],
    },
    {
      id: 'dates', title: 'Dates & Contingency', icon: 'calendar-days',
      fields: [
        PDT('effectiveDate', 'Effective date', { required: true, span: 1, help: 'Date the PA is signed.' }),
        PDT('closingDate', 'Closing date (no later than)', { required: true, span: 1, help: 'Latest acceptable closing — the actual closing date is mutually agreed.' }),
        PSEL('contingencyPeriodDays', 'Inspection contingency period (days)', CONTINGENCY_DAY_OPTIONS, { required: true, span: 2, help: 'Buyer\'s due-diligence window. Standard 30–60 days.' }),
      ],
    },
    {
      id: 'title', title: 'Title & Closing', icon: 'shield-check',
      fields: [
        PT('titleCompanyName', 'Title company', { required: true, span: 2, placeholder: 'Land Title, Inc.', help: 'Holds earnest money + issues title policy. Halie can confirm CEG\'s preferred title companies.' }),
      ],
    },
    {
      id: 'broker', title: 'Brokers', icon: 'briefcase',
      fields: [
        PSEL('broker', 'CEG broker (Buyer\'s broker)', PA_BROKERS, {
          required: true, span: 1,
          help: 'Email auto-fills from the CEG directory.',
          cascade: PA_BROKER_EMAIL_CASCADE,
        }),
        PEML('brokerEmail', 'CEG broker email', { required: true, span: 1, placeholder: 'broker@cegspaces.com' }),
        PT('buyerBrokerCommissionPct', 'Buyer\'s broker commission %', { required: true, span: 1, placeholder: '3', help: 'Typical 2–3%. Outside that range needs Halie\'s review.' }),
        PT('sellersBrokerName', 'Seller\'s broker (if any)', { span: 1, placeholder: 'N/A or "Acme Realty"', help: 'If no seller-side broker, leave blank or type "N/A".' }),
      ],
    },
    {
      id: 'notice', title: 'Notice Addresses', icon: 'mail',
      fields: [
        PT('buyerAddressLine1', 'Buyer street address', { required: true, span: 2, placeholder: '100 Washington Ave S, Suite 1500' }),
        PT('buyerAddressLine2', 'Buyer city/state/ZIP', { required: true, span: 2, placeholder: 'Minneapolis, MN 55401' }),
        PEML('buyerEmail', 'Buyer email', { required: true, span: 2, placeholder: 'patricia@northstaracq.com' }),
        PT('sellerAddressLine1', 'Seller street address', { required: true, span: 2, placeholder: '8200 Penn Ave S' }),
        PT('sellerAddressLine2', 'Seller city/state/ZIP', { required: true, span: 2, placeholder: 'Bloomington, MN 55431' }),
        PEML('sellerEmail', 'Seller email', { required: true, span: 2, placeholder: 'curtis@pennavecapital.com' }),
      ],
    },
  ],
};

// ─── Draft template — abbreviated preview (full PA text is 30+ pages) ───
// We render the SECTION HEADERS and key clauses. The complete legal text
// is in the .docx. The preview is enough for the broker to know what
// they're sending.

const FPA = (v, ph) => <FilledPA>{v || ph}</FilledPA>;

function paFmtDate(iso) {
  if (!iso) return '[MONTH DAY, YEAR]';
  const d = new Date(iso + 'T00:00:00');
  if (isNaN(d.getTime())) return iso;
  return d.toLocaleDateString('en-US', { month: 'long', day: 'numeric', year: 'numeric' });
}

function paFmtMoney(s) {
  if (!s) return null;
  const n = parseFloat(String(s).replace(/[$,]/g, ''));
  if (isNaN(n)) return s;
  return '$' + n.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
}

const TEMPLATE_PURCHASE_AGREEMENT = (v) => [
  {
    id: 'parties', title: 'Parties & Recitals', legalRef: '§ 1',
    body: (
      <>
        <p style={{textAlign:'center', textTransform:'uppercase', letterSpacing:'0.08em', fontWeight:700, fontSize:18, color:'var(--ceg-navy)', marginBottom: 18}}>Purchase Agreement</p>
        <p>
          This Real Estate Purchase Agreement ("Agreement") is made and entered into as of {FPA(paFmtDate(v.effectiveDate), '[MONTH DAY, YEAR]')} (the "Effective Date"), by and between {FPA(v.buyerEntity, '[BUYER NAME]')}, {FPA(v.buyerEntityType, '[A MINNESOTA LLC / INDIVIDUAL / ETC.]')}, and/or its assigns ("Buyer"), and {FPA(v.sellerEntity, '[SELLER NAME]')} ("Seller").
        </p>
        <p style={{marginTop:14, fontWeight:600, color:'var(--ink-700)', textTransform:'uppercase', letterSpacing:'0.06em', fontSize:13}}>Recitals</p>
        <p>
          WHEREAS, Seller is the owner of certain improved real property, including an approximately {FPA(v.propertySquareFootage, '[SQUARE FOOTAGE]')} square foot commercial building located at {FPA(v.propertyAddress && v.propertyCity && v.propertyZip ? `${v.propertyAddress}, ${v.propertyCity}, MN ${v.propertyZip}` : null, '[PROPERTY ADDRESS, CITY, MN ZIP]')}.
        </p>
      </>
    ),
  },
  {
    id: 'definitions', title: 'Definitions', legalRef: '§ 1',
    body: (
      <p style={{fontStyle:'italic', color:'var(--ink-500)'}}>
        Standard CEG definitions apply (Closing, Closing Date, Contingency Period, Deed, Earnest Money, Improvements, Land, Leases, Permits, Personal Property, Plans, Property, Title Commitment, Title Company, Title Evidence, Warranties). Closing date no later than {FPA(paFmtDate(v.closingDate), '[CLOSING DATE]')}. Inspection contingency period: {FPA(v.contingencyPeriodDays, '[XX]')} days from Effective Date. Title company: {FPA(v.titleCompanyName, '[TITLE COMPANY NAME]')}.
      </p>
    ),
  },
  {
    id: 'price', title: 'Purchase Price', legalRef: '§ 3',
    body: (
      <>
        <p>
          The purchase price (the "Purchase Price") for the Property shall be {FPA(v.purchasePriceWords, '[PURCHASE PRICE WRITTEN OUT]')} and 00/100 Dollars ({FPA(paFmtMoney(v.purchasePriceNumeric), '[$PURCHASE PRICE]')}), plus any closing adjustments in favor of Seller, minus any closing adjustments in favor of Buyer.
        </p>
        <p style={{marginTop:12}}>
          <strong>Earnest Money.</strong> {FPA(v.earnestMoneyWords, '[EARNEST MONEY WRITTEN OUT]')} and 00/100 Dollars ({FPA(paFmtMoney(v.earnestMoneyNumeric), '[$EARNEST MONEY]')}) to be held by {FPA(v.titleCompanyName, '[TITLE COMPANY NAME]')} in escrow, deposited within five (5) business days following the Effective Date.
        </p>
      </>
    ),
  },
  {
    id: 'closing', title: 'Closing', legalRef: '§ 4',
    body: (
      <p style={{fontStyle:'italic', color:'var(--ink-500)'}}>
        Closing on the Closing Date at the Title Company. Standard CEG buyer + seller deliveries (deed, bill of sale, FIRPTA, closing statement, assignment & assumption agreement, etc.). Possession transfers immediately after Closing.
      </p>
    ),
  },
  {
    id: 'title-exam', title: 'Title Examination & Costs', legalRef: '§ 5',
    body: (
      <p style={{fontStyle:'italic', color:'var(--ink-500)'}}>
        Standard CEG title exam process (15 days for Buyer to object; 30 days for Seller to cure). Standard cost split: Seller pays title commitment, half of escrow fee, deed tax, and real estate commissions. Buyer pays recording costs, title insurance premium, half of escrow fee.
      </p>
    ),
  },
  {
    id: 'contingency', title: 'Due Diligence & Contingencies', legalRef: '§ 6',
    body: (
      <p>
        Seller delivers due-diligence documents within 3 days of the Effective Date. Buyer has <strong>{FPA(v.contingencyPeriodDays, '[XX]')} days</strong> from the Effective Date to inspect and waive contingencies. Financing contingency: additional 15-day period after the inspection contingency expires.
      </p>
    ),
  },
  {
    id: 'commissions', title: 'Real Estate Commissions', legalRef: '§ 9',
    body: (
      <p>
        Seller shall pay <strong>Commercial Equities Group, Inc.</strong> (Buyer's Broker) a commission at Closing equal to {FPA(v.buyerBrokerCommissionPct ? v.buyerBrokerCommissionPct + '%' : null, '[X]%')} of the Purchase Price. Seller's Broker: {FPA(v.sellersBrokerName, '[SELLER\'S BROKER NAME]')}.
      </p>
    ),
  },
  {
    id: 'representations', title: 'Representations & Warranties', legalRef: '§ 11',
    body: (
      <p style={{fontStyle:'italic', color:'var(--ink-500)'}}>
        Standard CEG seller representations (authority, ownership, no notice of code violations, zoning compliance, no pending litigation, no underground storage tanks, no individual sewage system, no well, no condemnation, no methamphetamine production, environmental disclosures, current zoning by City of {FPA(v.propertyCity, '[CITY]')}). Seller's "knowledge" defined as actual knowledge of {FPA(v.sellerRepresentativeName, '[SELLER REPRESENTATIVE NAME]')}. Seller reps survive 2 years; Buyer reps survive 1 year.
      </p>
    ),
  },
  {
    id: 'governance', title: 'Default, Notice, & Governing Law', legalRef: '§ 12–17',
    body: (
      <>
        <p style={{fontStyle:'italic', color:'var(--ink-500)'}}>
          Standard CEG default provisions (10-day cure; Buyer's remedies include Earnest Money refund, specific performance, or damages; Seller's sole remedy is Earnest Money as liquidated damages). Mutual indemnification surviving Closing.
        </p>
        <p style={{marginTop:12, fontStyle:'italic', color:'var(--ink-500)'}}>
          Notice addresses: Seller at {FPA(v.sellerAddressLine1, '[ADDRESS LINE 1]')}, {FPA(v.sellerAddressLine2, '[ADDRESS LINE 2]')}, {FPA(v.sellerEmail, '[SELLER EMAIL]')}. Buyer at {FPA(v.buyerAddressLine1, '[ADDRESS LINE 1]')}, {FPA(v.buyerAddressLine2, '[ADDRESS LINE 2]')}, {FPA(v.buyerEmail, '[BUYER EMAIL]')}.
        </p>
        <p style={{marginTop:12, fontStyle:'italic', color:'var(--ink-500)'}}>
          Governed by Minnesota law. Venue: state or federal court in {FPA(v.propertyCounty, '[COUNTY]')} County, Minnesota. Standard exclusivity, time-is-of-the-essence, counterpart, and assignment provisions.
        </p>
      </>
    ),
  },
  {
    id: 'exhibits', title: 'Exhibits', legalRef: '',
    body: (
      <p style={{fontStyle:'italic', color:'var(--ink-500)'}}>
        Exhibit A (Legal Description — to be inserted), Exhibit B (Seller's Documents list), Exhibit C (Rent Roll), Exhibit D (Permitted Exceptions), Exhibit E (Assigned Contracts), Exhibit F (Form of Assignment & Assumption Agreement), Exhibit G (Escrow Receipt with {FPA(v.titleCompanyName, '[TITLE COMPANY NAME]')}).
      </p>
    ),
  },
];

// ─── Demo values ──────────────────────────────────────────────────────

const DEMO_PURCHASE_AGREEMENT = {
  effectiveDate: '2026-05-14',
  closingDate: '2026-08-15',
  contingencyPeriodDays: '60',

  propertyAddress: '8200 Penn Ave S',
  propertyCity: 'Bloomington',
  propertyZip: '55431',
  propertyCounty: 'Hennepin',
  propertySquareFootage: '14,200',

  buyerEntity: 'Northstar Industrial Acquisitions LP',
  buyerEntityType: 'a Minnesota limited partnership',
  buyerAddressLine1: '100 Washington Ave S, Suite 1500',
  buyerAddressLine2: 'Minneapolis, MN 55401',
  buyerEmail: 'patricia@northstaracq.com',

  sellerEntity: 'Penn Ave Capital LLC',
  sellerAddressLine1: '8200 Penn Ave S',
  sellerAddressLine2: 'Bloomington, MN 55431',
  sellerEmail: 'curtis@pennavecapital.com',
  sellerRepresentativeName: 'Curtis Walsh',

  purchasePriceNumeric: '3,750,000',
  purchasePriceWords: 'Three Million Seven Hundred Fifty Thousand',
  earnestMoneyNumeric: '75,000',
  earnestMoneyWords: 'Seventy-Five Thousand',

  titleCompanyName: 'Land Title, Inc.',
  buyerBrokerCommissionPct: '3',
  sellersBrokerName: 'N/A',

  broker: 'Brian Potratz',
  brokerEmail: 'brian@cegspaces.com',
};

// ─── Register ─────────────────────────────────────────────────────────
window.FORM_SCHEMAS['purchase-agreement'] = SCHEMA_PURCHASE_AGREEMENT;
window.DRAFT_TEMPLATES['purchase-agreement'] = TEMPLATE_PURCHASE_AGREEMENT;
window.DEMO_VALUES['purchase-agreement'] = DEMO_PURCHASE_AGREEMENT;
