/* PLANS (C) — editorial Pattern Book library + plan detail */

const M = window.MAF;

const PLAN_CATALOG = {
  cottage1: { name: 'Cottage 1', style: 'Vernacular',     sqft: 1980, bd: 3, ba: 2.5, type: 'cottage', stories: 2, builders: ['artisan','dreambuilt','southhaven'] },
  cottage2: { name: 'Cottage 2', style: 'Tidewater',      sqft: 2240, bd: 3, ba: 2.5, type: 'cottage', stories: 2, builders: ['athens','dreambuilt','southernlux'] },
  cottage3: { name: 'Cottage 3', style: 'Lowcountry',     sqft: 2120, bd: 3, ba: 2.5, type: 'cottage', stories: 2, builders: ['artisan','macallan','southernlux'] },
  cottage4: { name: 'Cottage 4', style: 'European',       sqft: 2480, bd: 4, ba: 3,   type: 'cottage', stories: 2, builders: ['athens','macallan','southhaven'] },
  estate1:  { name: 'Estate Home 1', style: 'Greek Revival',  sqft: 3420, bd: 4, ba: 3.5, type: 'estate', stories: 2, builders: ['artisan','dreambuilt'] },
  estate2:  { name: 'Estate Home 2', style: 'Tidewater',      sqft: 3680, bd: 4, ba: 3.5, type: 'estate', stories: 2, builders: ['artisan','macallan','southhaven'] },
  estate3:  { name: 'Estate Home 3', style: 'European',       sqft: 4120, bd: 5, ba: 4.5, type: 'estate', stories: 2, builders: ['athens','macallan','southernlux'] },
  estate4:  { name: 'Estate Home 4', style: 'Lowcountry',     sqft: 3880, bd: 4, ba: 4,   type: 'estate', stories: 2, builders: ['dreambuilt','southhaven','southernlux'] },
  estate5:  { name: 'Estate Home 5', style: 'Shingle',        sqft: 4640, bd: 5, ba: 5,   type: 'estate', stories: 2, builders: ['athens','macallan','southernlux'] },
};
window.MAF.PLAN_CATALOG = PLAN_CATALOG;

const PLAN_ORDER = ['cottage1','cottage2','cottage3','cottage4','estate1','estate2','estate3','estate4','estate5'];

function PlansLibrary() {
  const { navigate } = M.useRoute();
  const data = M.useData();
  const [styleFilter, setStyleFilter] = React.useState('all');
  const [typeFilter, setTypeFilter] = React.useState('all');

  const all = PLAN_ORDER.map(id => ({ id, ...PLAN_CATALOG[id] }));
  const filtered = all.filter(p => {
    if (styleFilter !== 'all' && p.style !== styleFilter) return false;
    if (typeFilter !== 'all' && p.type !== typeFilter) return false;
    return true;
  });

  const styles = Array.from(new Set(all.map(p => p.style)));

  return (
    <div className="wf-screen col" style={{ minHeight: '100vh' }}>
      <M.TopNav />

      {/* featured plan */}
      <div className="row" style={{ padding: "40px 40px", gap: 40 }}>
        <M.Img label="Estate Home 2 · featured rendering" style={{ flex: 3, height: 480, cursor: 'pointer' }}
               onClick={() => navigate('plan', { id: 'estate2' })}/>
        <div className="col grow" style={{ flex: 2, paddingTop: 20 }}>
          <M.Eyebrow>The Pattern Book · Architecture by Lew Oliver</M.Eyebrow>
          <div className="t-h1" style={{ fontSize: 60, fontStyle: "italic", fontWeight: 400, lineHeight: 1.05, marginTop: 12 }}>
            Nine plans,<br/>one book.
          </div>
          <M.Note style={{ fontSize: 14, marginTop: 18, maxWidth: 380 }}>
            Cottages and estates drawn for Madison Fields, anchored to the architectural
            traditions curated by the design board. Owners may also go fully custom,
            within the Pattern Book and ARB Guidelines.
          </M.Note>
          <div className="row gap-2" style={{ marginTop: 24, flexWrap: 'wrap' }}>
            <button className={"wf-chip" + (styleFilter === 'all' ? ' wf-chip-filled' : '')}
                    onClick={() => setStyleFilter('all')} style={{ cursor: 'pointer' }}>All {all.length}</button>
            {styles.map(s => {
              const n = all.filter(p => p.style === s).length;
              return (
                <button key={s} className={"wf-chip" + (styleFilter === s ? ' wf-chip-filled' : '')}
                        onClick={() => setStyleFilter(s)} style={{ cursor: 'pointer' }}>
                  {s} · {n}
                </button>
              );
            })}
          </div>
          <div className="row gap-2" style={{ marginTop: 12 }}>
            <button className={"wf-chip" + (typeFilter === 'all' ? ' wf-chip-filled' : '')} style={{ cursor: 'pointer' }} onClick={() => setTypeFilter('all')}>Any lot type</button>
            <button className={"wf-chip" + (typeFilter === 'cottage' ? ' wf-chip-filled' : '')} style={{ cursor: 'pointer' }} onClick={() => setTypeFilter('cottage')}>Cottage</button>
            <button className={"wf-chip" + (typeFilter === 'estate' ? ' wf-chip-filled' : '')} style={{ cursor: 'pointer' }} onClick={() => setTypeFilter('estate')}>Estate</button>
          </div>
          <div className="row gap-2" style={{ marginTop: 24 }}>
            <button className="wf-btn">Open Pattern Book PDF ↓</button>
            <button className="wf-btn wf-btn-ghost" onClick={() => navigate('siteplan')}>Filter by lot →</button>
          </div>
        </div>
      </div>

      {/* grid */}
      <div className="col gap-3" style={{ padding: "32px 40px 56px", background: "var(--bg-secondary)" }}>
        <div className="row between center">
          <M.Eyebrow>Browse {filtered.length} of {all.length} plans</M.Eyebrow>
          <M.Eyebrow>Sort · Square feet ↑</M.Eyebrow>
        </div>
        <div className="row gap-3" style={{ flexWrap: 'wrap' }}>
          {filtered.map(p => (
            <div key={p.id} className="wf-card col" style={{ padding: 0, flex: '0 0 calc(25% - 12px)', cursor: 'pointer' }}
                 onClick={() => navigate('plan', { id: p.id })}>
              <M.Img label={p.name} style={{ height: 240, borderRadius: 0, border: 'none' }}/>
              <div className="col gap-1" style={{ padding: 14 }}>
                <div className="row between center">
                  <M.Eyebrow>{p.style}</M.Eyebrow>
                  <M.Eyebrow>{p.type === 'cottage' ? 'Cottage' : 'Estate'}</M.Eyebrow>
                </div>
                <div className="t-h5">{p.name}</div>
                <M.Note style={{ fontSize: 12 }}>{p.sqft.toLocaleString()} sf · {p.bd} bd · {p.ba} ba</M.Note>
              </div>
            </div>
          ))}
        </div>
      </div>

      <M.Footer />
    </div>
  );
}

/* Plan detail — Plans C "magazine spread" */
function PlanDetail() {
  const { route, navigate } = M.useRoute();
  const plan = PLAN_CATALOG[route.id];
  const data = M.useData();
  if (!plan) {
    return (
      <div className="wf-screen col" style={{ minHeight: '100vh' }}>
        <M.TopNav />
        <div className="col center" style={{ flex: 1, padding: 80 }}>
          <M.Eyebrow>Unknown plan</M.Eyebrow>
          <button className="wf-btn" style={{ marginTop: 16 }} onClick={() => navigate('plans')}>Back to Pattern Book →</button>
        </div>
      </div>
    );
  }
  // Compatible lots: same type
  const compatLots = data.lots.filter(l => l.type === plan.type);
  const builderNames = plan.builders.map(id => data.builders.find(b => b.id === id)?.name).filter(Boolean);

  return (
    <div className="wf-screen col" style={{ minHeight: '100vh' }}>
      <M.TopNav />

      <div className="row gap-2 center" style={{ padding: "14px 40px", borderBottom: "1px solid var(--neutral-200)" }}>
        <M.Eyebrow style={{ cursor: 'pointer' }} onClick={() => navigate('plans')}>← Pattern Book</M.Eyebrow>
        <span style={{ color: "var(--neutral-300)" }}>/</span>
        <M.Eyebrow style={{ color: 'var(--neutral-900)' }}>{plan.name}</M.Eyebrow>
      </div>

      <div className="col" style={{ padding: "72px 40px 32px", textAlign: "center", gap: 12 }}>
        <M.Eyebrow>Plan No. {(PLAN_ORDER.indexOf(route.id) + 1).toString().padStart(2,'0')} · {plan.style}</M.Eyebrow>
        <div className="t-h1" style={{ fontSize: 96, fontStyle: "italic", fontWeight: 400 }}>{plan.name}</div>
        <M.Note style={{ maxWidth: 540, alignSelf: "center" }}>
          A {plan.bd}-bedroom {plan.style} plan for {plan.type === 'cottage' ? 'a cottage' : 'an estate'} homesite. Built by {builderNames.join(' or ')}.
          Anchored to the Madison Fields Pattern Book and ARB Guidelines.
        </M.Note>
      </div>

      <div className="row" style={{ padding: "0 40px 32px", gap: 12, justifyContent: "center" }}>
        {[
          [plan.sqft.toLocaleString(), "Sq. feet"],
          [`${plan.bd} / ${plan.ba}`, "Bd / Ba"],
          [plan.stories, "Stories"],
          [builderNames.length, "Builders"],
          [plan.style, "Style"],
        ].map(([v, l], i) => (
          <div key={i} className="col center" style={{
            flex: 1, padding: "20px 12px",
            border: "1px solid var(--neutral-200)", borderRadius: 4
          }}>
            <div className="t-h3" style={{ fontStyle: "italic", fontWeight: 400 }}>{v}</div>
            <M.Eyebrow style={{ marginTop: 4 }}>{l}</M.Eyebrow>
          </div>
        ))}
      </div>

      <div className="row" style={{ padding: "0 40px", gap: 24, marginBottom: 32 }}>
        <M.Img label="ground floor plan · large" style={{ flex: 1, height: 400 }} />
        <M.Img label="second floor plan · large" style={{ flex: 1, height: 400 }} />
      </div>

      <div className="row" style={{ padding: "0 40px 56px", gap: 24 }}>
        <M.Img label="front elevation" style={{ flex: 1, height: 240 }} />
        <M.Img label="rear elevation" style={{ flex: 1, height: 240 }} />
        <M.Img label="material palette" style={{ flex: 1, height: 240 }} />
      </div>

      {/* compatible lots */}
      <div className="col" style={{ padding: "32px 40px 56px", background: 'var(--bg-secondary)' }}>
        <div className="row between center" style={{ marginBottom: 16 }}>
          <div className="col">
            <M.Eyebrow>Compatible lots · {compatLots.length} in Madison Fields</M.Eyebrow>
            <div className="t-h3" style={{ marginTop: 4 }}>Where this plan can sit.</div>
          </div>
          <button className="wf-btn" onClick={() => navigate('siteplan')}>See on the site plan →</button>
        </div>
        <div style={{ background: 'var(--bg-primary)', border: '1px solid var(--neutral-200)', borderRadius: 4 }}>
          <PlanCompatLotsMap planType={plan.type} height={420}/>
        </div>
      </div>

      <div className="row between center" style={{
        padding: "24px 40px",
        borderTop: "1px solid var(--neutral-200)",
        background: 'var(--bg-primary)'
      }}>
        <M.Eyebrow>{compatLots.length} lots welcome this plan · {builderNames.join(' and ')} build{builderNames.length === 1 ? 's' : ''} it</M.Eyebrow>
        <div className="row gap-2">
          <button className="wf-btn wf-btn-ghost">Download brochure ↓</button>
          <button className="wf-btn" onClick={() => navigate('siteplan')}>See compatible lots →</button>
        </div>
      </div>

      <M.Footer />
    </div>
  );
}

function PlanCompatLotsMap({ planType, height = 420 }) {
  const { navigate } = M.useRoute();
  const filters = {
    type: { cottage: planType === 'cottage', estate: planType === 'estate' },
    status: { available: true, reserved: true, sold: true, soon: true },
    price: 'all', builder: 'all'
  };
  return (
    <M.SitePlanMap
      filters={filters}
      showAerial={true}
      onSelect={(l) => navigate('lot', { n: l.n })}
      height={height}
    />
  );
}

window.MAF.PlansLibrary = PlansLibrary;
window.MAF.PlanDetail = PlanDetail;
