/* LOT DETAIL (C) — editorial long-scroll */

const M = window.MAF;

function LotPage() {
  const { route, navigate } = M.useRoute();
  const lot = M.useLot(route.n);
  const data = M.useData();
  if (!lot) {
    return (
      <div className="wf-screen col" style={{ minHeight: '100vh' }}>
        <M.TopNav />
        <div className="col center" style={{ flex: 1, padding: 80, gap: 16 }}>
          <M.Eyebrow>Lot not found</M.Eyebrow>
          <div className="t-h2">No lot in this neighborhood with that number.</div>
          <button className="wf-btn" onClick={() => navigate('siteplan')}>Back to site plan →</button>
        </div>
      </div>
    );
  }
  const builder = data.builders.find(b => b.id === lot.builderId);
  const ordinal = (() => {
    const n = lot.n;
    const s = ['th','st','nd','rd'][((n%100-20)%10) >= 4 || (n%100) <= 20 ? 0 : (n%10)];
    return n + s;
  })();
  // Plans compatible — use the global catalog and pick from the builder's plan list
  const planCatalog = window.MAF.PLAN_CATALOG || {};
  const builderPlanIds = (builder?.plans || []).filter(id => planCatalog[id]?.type === lot.type);
  const planIds = builderPlanIds.slice(0, 3);
  // Fall back to type-appropriate plans if builder has fewer than 3
  if (planIds.length < 3) {
    Object.keys(planCatalog).filter(id => planCatalog[id].type === lot.type).forEach(id => {
      if (!planIds.includes(id) && planIds.length < 3) planIds.push(id);
    });
  }
  const plans = planIds.map(id => ({ id, ...planCatalog[id] }));

  const orientation = (() => {
    // pseudo from lot.n — kept stable
    const opts = ['South','Southwest','West','East','North','Northeast'];
    return opts[lot.n % opts.length];
  })();
  const slope = lot.n % 4 === 0 ? 'Mild · east-west' : lot.n % 4 === 1 ? 'Gentle · north-south' : lot.n % 4 === 2 ? 'Mild · west-east' : 'Level';
  const adjacency = lot.n % 3 === 0 ? 'Hardwoods to east' : lot.n % 3 === 1 ? 'Greenspace frontage' : 'Interior, mature trees both sides';
  const frontage = 90 + (lot.n % 8) * 8;

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

      {/* hero */}
      <div style={{ position: "relative", height: 620 }}>
        <M.Img dark label={`single hero · drone, lot ${lot.n}`}
               style={{ position: "absolute", inset: 0, borderRadius: 0, border: "none" }} />
        <div className="col center" style={{
          position: "absolute", inset: 0, paddingTop: 110, textAlign: "center", zIndex: 2
        }}>
          <M.Eyebrow style={{ color: "rgba(251,251,249,0.7)" }}>
            Lot {lot.n} · {lot.type === 'cottage' ? 'Cottage' : 'Estate'} · Phase One
          </M.Eyebrow>
          <div className="t-h1" style={{
            color: "var(--bg-primary)", fontSize: 124, marginTop: 14,
            fontStyle: "italic", fontWeight: 400, lineHeight: 1.0
          }}>
            The {ordinal}.
          </div>
          <M.Note style={{ color: "rgba(251,251,249,0.8)", maxWidth: 560, marginTop: 14, fontSize: 14 }}>
            {slope}, {adjacency.toLowerCase()}, {orientation.toLowerCase()} orientation.
          </M.Note>
        </div>

        <div className="row between center" style={{
          position: "absolute", bottom: 0, left: 0, right: 0,
          padding: "20px 40px", color: "var(--bg-primary)",
          background: "linear-gradient(to top, rgba(0,0,0,0.4), transparent)",
          zIndex: 2
        }}>
          <M.Eyebrow style={{ color: "rgba(251,251,249,0.75)" }}>
            {lot.acres} ac · {frontage} ft frontage · {builder?.name}
          </M.Eyebrow>
          <M.Eyebrow style={{ color: "rgba(251,251,249,0.75)" }}>Scroll for the walkthrough ↓</M.Eyebrow>
        </div>

        {/* save / share */}
        <div className="row gap-2" style={{ position: 'absolute', top: 80, right: 24, zIndex: 3 }}>
          <span className="wf-chip" style={{ background: "rgba(28,25,23,0.6)", borderColor: "transparent", color: "var(--bg-primary)" }}>♡ Save</span>
          <span className="wf-chip" style={{ background: "rgba(28,25,23,0.6)", borderColor: "transparent", color: "var(--bg-primary)" }}>⇪ Share</span>
        </div>
      </div>

      {/* breadcrumb / nav */}
      <div className="row between center" style={{ padding: "14px 40px", borderBottom: "1px solid var(--neutral-200)" }}>
        <div className="row gap-2 center">
          <M.Eyebrow style={{ cursor: 'pointer' }} onClick={() => navigate('siteplan')}>← Site Plan</M.Eyebrow>
          <span style={{ color: "var(--neutral-300)" }}>/</span>
          <M.Eyebrow style={{ color: 'var(--neutral-900)' }}>Lot {lot.n}</M.Eyebrow>
        </div>
        <div className="row gap-3 center">
          <M.StatusChip tone={M.STATUS_DOT[lot.status]} label={M.STATUS_LABEL[lot.status]} />
          <M.Eyebrow>{builder?.name} · {plans.length} plans compatible</M.Eyebrow>
          <button className="wf-chip" style={{ cursor: 'pointer' }}
                  onClick={() => navigate('lot', { n: Math.max(1, lot.n - 1) })}>← Lot {Math.max(1, lot.n - 1)}</button>
          <button className="wf-chip" style={{ cursor: 'pointer' }}
                  onClick={() => navigate('lot', { n: Math.min(data.count, lot.n + 1) })}>Lot {Math.min(data.count, lot.n + 1)} →</button>
        </div>
      </div>

      {/* chapter I — facts grid */}
      <div className="col center" style={{ padding: "72px 40px 32px", gap: 16, textAlign: "center" }}>
        <M.Eyebrow>I · The lot</M.Eyebrow>
        <div className="t-h2" style={{ maxWidth: 720, fontSize: 40, fontStyle: "italic", fontWeight: 400 }}>
          {lot.type === 'cottage' ? 'Cottage' : 'Estate'}, {orientation.toLowerCase()}-facing, with {adjacency.toLowerCase()}.
        </div>
      </div>
      <div className="row" style={{ padding: "0 40px 56px", gap: 12, justifyContent: "center" }}>
        {[
          [lot.acres, "Acres"],
          [`${frontage}'`, "Frontage"],
          [orientation[0], "Orientation"],
          [adjacency.includes('Greenspace') ? 'Grn' : adjacency.includes('Hardwoods') ? 'Hwd' : 'Int', "View"],
          [slope.includes('Level') ? 'Level' : slope.split(' ')[0], "Slope"],
        ].map(([v, l], i) => (
          <div key={i} className="col center" style={{
            flex: 1, padding: "22px 16px",
            border: "1px solid var(--neutral-200)", borderRadius: 4
          }}>
            <div className="t-h2" style={{ fontSize: 36, fontStyle: "italic", fontWeight: 400 }}>{v}</div>
            <M.Eyebrow style={{ marginTop: 6 }}>{l}</M.Eyebrow>
          </div>
        ))}
      </div>

      {/* chapter II — where it sits */}
      <div className="row" style={{ padding: "32px 40px", gap: 40, background: "var(--bg-secondary)" }}>
        <div className="col grow" style={{ maxWidth: 380, paddingTop: 24 }}>
          <M.Eyebrow>II · Where it sits</M.Eyebrow>
          <div className="t-h3" style={{ marginTop: 8 }}>
            On the {lot.c[0] > 0 ? 'east' : 'west'} side of the loop road, sheltered from view by hardwoods.
          </div>
          <M.Note style={{ fontSize: 13, marginTop: 12 }}>
            {lot.area_sqft.toLocaleString()} sq ft. Adjacent to {adjacency.toLowerCase()}.
            Walking distance to community amenities (under one quarter mile).
          </M.Note>
          <button className="wf-btn wf-btn-ghost" style={{ marginTop: 16, alignSelf: 'flex-start' }}
                  onClick={() => navigate('siteplan')}>
            Open in site plan →
          </button>
        </div>
        <div className="col grow" style={{ background: 'var(--bg-primary)', border: '1px solid var(--neutral-200)', borderRadius: 4 }}>
          <MiniSitePlan lotN={lot.n} height={360}/>
        </div>
      </div>

      {/* chapter III — plans */}
      <div className="col" style={{ padding: "72px 40px 32px", textAlign: "center", gap: 12 }}>
        <M.Eyebrow>III · Plans this homesite welcomes</M.Eyebrow>
        <div className="t-h2" style={{ fontSize: 40, fontStyle: "italic", fontWeight: 400, alignSelf: "center" }}>
          {plans.length} of the nine.
        </div>
      </div>
      <div className="row" style={{ padding: "16px 40px 56px", gap: 16 }}>
        {plans.map(p => (
          <div key={p.id} className="wf-card col" style={{ padding: 0, flex: 1, cursor: 'pointer' }}
               onClick={() => navigate('plan', { id: p.id })}>
            <M.Img label={`${p.name} · floor plan`} style={{ height: 200, borderRadius: 0, border: 'none' }}/>
            <div className="col gap-1" style={{ padding: 18 }}>
              <M.Eyebrow>{p.style}</M.Eyebrow>
              <div className="t-h4">{p.name}</div>
              <M.Note style={{ fontSize: 12 }}>{p.sqft.toLocaleString()} sf · {p.bd} bd · {p.ba} ba</M.Note>
            </div>
          </div>
        ))}
      </div>

      {/* chapter IV — the builder */}
      <div className="row" style={{ padding: "32px 40px 56px", gap: 48, background: 'var(--bg-secondary)' }}>
        <div className="col grow" style={{ maxWidth: 360, paddingTop: 16 }}>
          <M.Eyebrow>IV · The builder</M.Eyebrow>
          <div className="t-h2" style={{ fontSize: 40, marginTop: 8 }}>{builder?.name}</div>
          <M.Note style={{ fontSize: 13, marginTop: 12 }}>
            One of six builders approved for Madison Fields. Inquiries route through the team for a warm introduction.
          </M.Note>
          <button className="wf-btn wf-btn-ghost" style={{ marginTop: 16, alignSelf: 'flex-start' }}
                  onClick={() => navigate('builder', { id: builder.id })}>
            Open builder profile →
          </button>
        </div>
        <div className="col grow row gap-3" style={{ alignItems: 'stretch' }}>
          <M.Img label="principal portrait" style={{ flex: 1, height: 280 }}/>
          <M.Img label="recent work" style={{ flex: 1, height: 280 }}/>
        </div>
      </div>

      {/* reservation bar — homesite price only */}
      <div className="row between center" style={{
        padding: "32px 40px",
        borderTop: "1px solid var(--neutral-200)",
        background: "var(--bg-primary)"
      }}>
        <div className="col">
          <M.Eyebrow>Lot {lot.n} · {lot.type === 'cottage' ? 'Cottage' : 'Estate'} homesite</M.Eyebrow>
          <div className="row gap-3" style={{ alignItems: 'baseline' }}>
            <div className="t-h2" style={{ fontSize: 40 }}>{M.fmtPrice(lot.price)}</div>
            <M.Note style={{ fontSize: 12 }}>homesite only · home construction priced separately</M.Note>
          </div>
        </div>
        <div className="row gap-3">
          <button className="wf-btn wf-btn-ghost">♡ Save to favorites</button>
          <button className="wf-btn wf-btn-ghost">⇪ Share with spouse / agent</button>
          <button className="wf-btn">Reserve this Homesite →</button>
        </div>
      </div>

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

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

window.MAF.LotPage = LotPage;
