// reps.jsx — Real CEG Tenant Rep + Buyer Rep schemas + draft templates
// Source: CEG boilerplate Word docs (Tenant Rep, Buyer Rep).
// Mutates the schema/template/demo registries owned by data.jsx.
//
// Both docs are very simple compared to listing agreements — only two
// placeholder values (date + client name). The legal text is fully fixed.

const { Filled: FilledRep } = window;

// Pull broker directory + cascade from listings.jsx (loaded earlier in
// index.html). Single source of truth — adding a broker to the listings
// directory automatically makes them available here too.
const REPS_BROKERS = window.__BROKERS__ || [];
const REPS_BROKER_EMAIL_CASCADE = window.__BROKER_EMAIL_CASCADE__ || {};

// ─── Field-builder shorthand (local) ──────────────────────────────────
const Tr = (id, label, o={}) => ({ id, label, type: 'text', ...o });
const TAr = (id, label, o={}) => ({ id, label, type: 'textarea', ...o });
const DTr = (id, label, o={}) => ({ id, label, type: 'date', ...o });
const SELr = (id, label, options, o={}) => ({ id, label, type: 'select', options, ...o });
const EMLr = (id, label, o={}) => ({ id, label, type: 'email', ...o });
const TELr = (id, label, o={}) => ({ id, label, type: 'tel', ...o });

// ─── Reusable section builders ────────────────────────────────────────
const repClientSection = (label, partyNoun) => ({
  id: 'client', title: label, icon: 'briefcase',
  fields: [
    Tr('clientEntity', `${partyNoun} entity`, { required: true, span: 2, placeholder: 'Stinski Holdings LLC', help: 'Legal entity that will sign the agreement.' }),
    Tr('signatoryName', 'Signatory name', { required: true, span: 1, placeholder: 'Tom Stinski' }),
    Tr('signatoryTitle', 'Signatory title', { span: 1, placeholder: 'Managing Member' }),
    EMLr('clientEmail', `${partyNoun} email`, { required: true, span: 1, placeholder: 'tom@stinskiholdings.com' }),
    TELr('clientPhone', `${partyNoun} phone`, { span: 1, placeholder: '(612) 555-0188' }),
  ],
});

const repPeriodSection = () => ({
  id: 'period', title: 'Effective Date', icon: 'calendar-days',
  fields: [
    DTr('effectiveDate', 'Effective date', {
      required: true, span: 2,
      help: 'Term is fixed at 12 months from this date — the boilerplate doesn’t allow shorter or longer.',
    }),
  ],
});

const repAgentSection = () => ({
  id: 'agent', title: 'CEG Agent', icon: 'user-round',
  fields: [
    SELr('broker', 'CEG broker', REPS_BROKERS, {
      required: true, span: 1,
      help: 'Email auto-fills from the CEG directory.',
      cascade: REPS_BROKER_EMAIL_CASCADE,
    }),
    EMLr('brokerEmail', 'Broker email', { required: true, span: 1, placeholder: 'broker@cegspaces.com', help: 'Auto-filled when you pick a broker.' }),
  ],
});

// ════════════════════════════════════════════════════════════════════════
// SCHEMAS
// ════════════════════════════════════════════════════════════════════════

const SCHEMA_TENANT_REP = {
  title: 'Tenant Rep Agreement',
  subtitle: 'Tenant appoints CEG as exclusive representative for a Minnesota lease',
  sections: [
    repClientSection('Tenant', 'Tenant'),
    repPeriodSection(),
    repAgentSection(),
  ],
};

const SCHEMA_BUYER_REP = {
  title: 'Buyer Rep Agreement',
  subtitle: 'Client appoints CEG as exclusive representative for a Minnesota purchase or lease',
  sections: [
    repClientSection('Client', 'Client'),
    repPeriodSection(),
    repAgentSection(),
  ],
};

// ════════════════════════════════════════════════════════════════════════
// DRAFT TEMPLATES — faithful legal language from CEG boilerplates
// ════════════════════════════════════════════════════════════════════════

const FRep = (v, ph) => <FilledRep>{v || ph}</FilledRep>;

function repFmtDate(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' });
}

// Signature section is inlined per template (it needs `v` in scope for the
// client entity name) — see TEMPLATE_TENANT_REP / TEMPLATE_BUYER_REP below.

const TEMPLATE_TENANT_REP = (v) => [
  {
    id: 'parties', title: 'The Parties', legalRef: '§ 1',
    body: (
      <>
        <p style={{textAlign:'center', textTransform:'uppercase', letterSpacing:'0.08em', fontWeight:700, fontSize:18, color:'var(--ceg-navy)', marginBottom: 18}}>Tenant Representation Agreement</p>
        <p>
          This Tenant Representation Agreement ("Agreement") made on {FRep(repFmtDate(v.effectiveDate), '[MONTH DAY, YEAR]')} is by and between: {FRep(v.clientEntity, '[CLIENT NAME]')} ("Tenant") and <strong>Commercial Equities Group, Inc.</strong> ("Broker"). Collectively, the Tenant and Broker shall be referred to as the "Parties." Any person or entity with which the Tenant enters into a contractual agreement for the lease of real estate shall be referred to as "Owner" in this Agreement.
        </p>
      </>
    ),
  },
  {
    id: 'services', title: 'Services Provided', legalRef: '§ 2',
    body: (
      <p>
        Tenant hereby appoints Commercial Equities Group, Inc. as its exclusive representative for the purpose of securing a building and property lease within the State of Minnesota suitable to Tenant's needs. Tenant agrees to communicate exclusively with Broker in efforts to acquire a lease of real property meeting Tenant's wants and needs. The Commission, under an exclusive basis, is due and payable even in the event Tenant acquires a lease of real property without the assistance or involvement of the Broker.
      </p>
    ),
  },
  {
    id: 'period', title: 'Period of Agreement', legalRef: '§ 3',
    body: <p>This Agreement shall remain in effect for 12 months from the date of full execution.</p>,
  },
  {
    id: 'compensation', title: 'Compensation', legalRef: '§ 4',
    body: (
      <p>
        In the event a lease for real property is acquired, Broker will normally be compensated in the form of a commission from the owner of the building in which a lease agreement is executed. In the event the building owner or its representative is unwilling to fully compensate Broker the customary commission for the services provided, Client agrees to compensate the Broker the difference to fully satisfy Broker's commission.
      </p>
    ),
  },
  {
    id: 'disclaimer', title: 'Disclaimer', legalRef: '§ 5',
    body: (
      <p>
        Tenant acknowledges that the Broker is not a professional or expert in the matters of law, Federal or State tax codes, financing, surveying, engineering, architectural, structural, environmental, other physical conditions or non-physical details of real property. In addition, the Broker has advised and recommended the Tenant to seek expert assistance for advice on such matters. Broker makes no warranty or guarantee concerning the service of such experts or their products, the condition of property, the absence of defects therein, or the suitability of such property for Tenant's purposes.
      </p>
    ),
  },
  {
    id: 'governing', title: 'Governing Law', legalRef: '§ 6',
    body: <p>This Agreement shall be governed by and construed in accordance with the laws of the State of Minnesota.</p>,
  },
  {
    id: 'signatures', title: 'Signatures', legalRef: '§ 7',
    body: (
      <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:32, marginTop:24}}>
        <div>
          <p style={{fontWeight:600, color:'var(--ink-900)', marginBottom:24}}>Commercial Equities Group, Inc.</p>
          <p style={{borderBottom:'1px solid var(--ink-400)', paddingBottom:4, color:'var(--ink-500)', fontSize:12}}>Signature</p>
          <p style={{borderBottom:'1px solid var(--ink-400)', paddingBottom:4, color:'var(--ink-500)', fontSize:12, marginTop:14}}>Date</p>
        </div>
        <div>
          <p style={{fontWeight:600, color:'var(--ink-900)', marginBottom:24}}>{FRep(v.clientEntity, '[TENANT NAME]')}</p>
          <p style={{borderBottom:'1px solid var(--ink-400)', paddingBottom:4, color:'var(--ink-500)', fontSize:12}}>Signature</p>
          <p style={{borderBottom:'1px solid var(--ink-400)', paddingBottom:4, color:'var(--ink-500)', fontSize:12, marginTop:14}}>Date</p>
        </div>
      </div>
    ),
  },
];

const TEMPLATE_BUYER_REP = (v) => [
  {
    id: 'parties', title: 'The Parties', legalRef: '§ 1',
    body: (
      <>
        <p style={{textAlign:'center', textTransform:'uppercase', letterSpacing:'0.08em', fontWeight:700, fontSize:18, color:'var(--ceg-navy)', marginBottom: 18}}>Buyer Representation Agreement</p>
        <p>
          This Buyer Representation Agreement ("Agreement") made on {FRep(repFmtDate(v.effectiveDate), '[MONTH DAY, YEAR]')} is by and between: {FRep(v.clientEntity, '[CLIENT NAME]')} ("Client") and <strong>Commercial Equities Group, Inc.</strong> ("Broker"). Collectively, the Client and Broker shall be referred to as the "Parties."
        </p>
      </>
    ),
  },
  {
    id: 'services', title: 'Services Provided', legalRef: '§ 2',
    body: (
      <p>
        {FRep(v.clientEntity, '[CLIENT NAME]')} hereby appoints Commercial Equities Group, Inc. as its exclusive representative for the purpose of securing a location for its operation in the State of Minnesota or other locations that may be appropriate.
      </p>
    ),
  },
  {
    id: 'period', title: 'Period of Agreement', legalRef: '§ 3',
    body: <p>This Agreement shall remain in effect for 12 months from the date of full execution.</p>,
  },
  {
    id: 'compensation', title: 'Compensation', legalRef: '§ 4',
    body: (
      <p>
        This Agreement in no way obligates the Client to pay a fee to the Broker. The Broker will normally be compensated in the form of a commission from the building owner of the building in which a lease agreement or sale is executed. In the event the building owner or its representative is unwilling to fully compensate Broker the customary commission for the services provided, Client agrees to compensate the Broker the difference to fully satisfy Broker's commission.
      </p>
    ),
  },
  {
    id: 'disclaimer', title: 'Disclaimer', legalRef: '§ 5',
    body: (
      <p>
        Client acknowledges that the Broker is not a professional or expert in the matters of law, Federal or State tax codes, financing, surveying, engineering, architectural, structural, environmental, other physical conditions or non-physical details of real property. In addition, the Broker has advised and recommended the Client to seek expert assistance for advice on such matters. Broker makes no warranty or guarantee concerning the service of such experts or their products, the condition of property, the absence of defects therein, or the suitability of such property for Client's purposes.
      </p>
    ),
  },
  {
    id: 'governing', title: 'Governing Law', legalRef: '§ 6',
    body: <p>This Agreement shall be governed by and construed in accordance with the laws of the State of Minnesota.</p>,
  },
  {
    id: 'signatures', title: 'Signatures', legalRef: '§ 7',
    body: (
      <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:32, marginTop:24}}>
        <div>
          <p style={{fontWeight:600, color:'var(--ink-900)', marginBottom:24}}>Commercial Equities Group, Inc.</p>
          <p style={{borderBottom:'1px solid var(--ink-400)', paddingBottom:4, color:'var(--ink-500)', fontSize:12}}>Signature</p>
          <p style={{borderBottom:'1px solid var(--ink-400)', paddingBottom:4, color:'var(--ink-500)', fontSize:12, marginTop:14}}>Date</p>
        </div>
        <div>
          <p style={{fontWeight:600, color:'var(--ink-900)', marginBottom:24}}>{FRep(v.clientEntity, '[CLIENT NAME]')}</p>
          <p style={{borderBottom:'1px solid var(--ink-400)', paddingBottom:4, color:'var(--ink-500)', fontSize:12}}>Signature</p>
          <p style={{borderBottom:'1px solid var(--ink-400)', paddingBottom:4, color:'var(--ink-500)', fontSize:12, marginTop:14}}>Date</p>
        </div>
      </div>
    ),
  },
];

// ════════════════════════════════════════════════════════════════════════
// DEMO VALUES
// ════════════════════════════════════════════════════════════════════════

const DEMO_TENANT_REP = {
  clientEntity: 'Stinski Holdings LLC',
  signatoryName: 'Tom Stinski',
  signatoryTitle: 'Managing Member',
  clientEmail: 'tom@stinskiholdings.com',
  clientPhone: '(612) 555-0199',
  effectiveDate: '2026-05-14',
  broker: 'Brian Potratz',
  brokerEmail: 'brian@cegspaces.com',
};

const DEMO_BUYER_REP = {
  clientEntity: 'Northstar Industrial Acquisitions LP',
  signatoryName: 'Patricia Hennessey',
  signatoryTitle: 'General Partner',
  clientEmail: 'patricia@northstaracq.com',
  clientPhone: '(651) 555-0123',
  effectiveDate: '2026-05-14',
  broker: 'Halie Aarestad',
  brokerEmail: 'halie@cegspaces.com',
};

// ════════════════════════════════════════════════════════════════════════
// REGISTER (overwrites the placeholder entries seeded by data.jsx)
// ════════════════════════════════════════════════════════════════════════

window.FORM_SCHEMAS['tenant-rep'] = SCHEMA_TENANT_REP;
window.FORM_SCHEMAS['buyer-rep']  = SCHEMA_BUYER_REP;

window.DRAFT_TEMPLATES['tenant-rep'] = TEMPLATE_TENANT_REP;
window.DRAFT_TEMPLATES['buyer-rep']  = TEMPLATE_BUYER_REP;

window.DEMO_VALUES['tenant-rep'] = DEMO_TENANT_REP;
window.DEMO_VALUES['buyer-rep']  = DEMO_BUYER_REP;
