// Neal Communities — Home & Community detail (CRM) pages + inline Edit panel

const NIcon = {
  pencil: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" width="14" height="14"><path d="M12 20h9"/><path d="M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4z"/></svg>,
  share: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" width="14" height="14"><circle cx="18" cy="5" r="3"/><circle cx="6" cy="12" r="3"/><circle cx="18" cy="19" r="3"/><path d="M8.6 13.5l6.8 4M15.4 6.5l-6.8 4"/></svg>,
  download: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" width="14" height="14"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4M7 10l5 5 5-5M12 15V3"/></svg>,
  bed: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" width="15" height="15"><path d="M2 4v16M2 8h18a2 2 0 0 1 2 2v10M2 17h20M6 8V6a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>,
  ruler: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" width="15" height="15"><path d="M3 8l13 13 5-5L8 3z"/><path d="M7.5 7.5l1.5 1.5M11 4l1.5 1.5M14.5 7.5l1.5 1.5M7.5 11l1.5 1.5"/></svg>,
};

// ─── Reusable Edit panel (centered modal) ────────────────
function NealEditPanel({ title, fields, data, onSave, onClose }) {
  const [draft, setDraft] = React.useState(data);
  const set = (k, v) => setDraft(d => ({ ...d, [k]: v }));
  return (
    <div className="edit-overlay" onClick={onClose}>
      <div className="edit-modal" role="dialog" onClick={e => e.stopPropagation()}>
        <div className="edit-head">
          <div>
            <div className="eyebrow accent">{NIcon.pencil} EDIT</div>
            <div className="edit-title">{title}</div>
          </div>
          <div className="copilot-close" style={{color: 'var(--muted)'}} onClick={onClose}>
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" width="14" height="14"><path d="M18 6 6 18M6 6l12 12"/></svg>
          </div>
        </div>
        <div className="edit-body">
          {fields.map(f => (
            <div className="edit-field" key={f.key}>
              <label className="edit-label">{f.label}</label>
              {f.type === 'textarea'
                ? <textarea className="edit-input" rows={4} value={draft[f.key] || ''} onChange={e => set(f.key, e.target.value)}/>
                : f.type === 'select'
                ? <select className="edit-input" value={draft[f.key] || ''} onChange={e => set(f.key, e.target.value)}>
                    {f.options.map(o => <option key={o} value={o}>{o}</option>)}
                  </select>
                : <input className="edit-input" value={draft[f.key] || ''} onChange={e => set(f.key, e.target.value)}/>}
            </div>
          ))}
          <div className="edit-ai">{NI.sparkle} The Neal Assistant can rewrite the description or suggest an incentive — just ask in the chat.</div>
        </div>
        <div className="edit-foot">
          <button className="btn ghost" onClick={onClose}>Cancel</button>
          <button className="btn" onClick={() => { onSave(draft); onClose(); }}>Save changes</button>
        </div>
      </div>
    </div>
  );
}

// ─── Interested-buyer row ────────────────────────────────
function InterestedRow({ b, onClick, last }) {
  return (
    <div onClick={onClick} className="enroll-mini" style={{borderBottom: last ? 0 : '1px solid var(--border)', padding: '12px 0'}}>
      <div className="av" style={{background: b.color}}>{b.initials}</div>
      <div style={{flex: 1, minWidth: 0}}>
        <div className="av-name">{b.name}</div>
        <div className="av-meta">{b.id} · {b.meta}</div>
      </div>
      <span className="pill" style={{fontSize: 10.5}}>{b.status}</span>
      <span className="pill orange" style={{fontSize: 10.5}}>{b.score}</span>
    </div>
  );
}

// ═══ HOME DETAIL ═════════════════════════════════════════
function NealHomeDetail({ home, onBack, onSelectPerson, onSelectCommunity }) {
  const D = window.NealData;
  const [data, setData] = React.useState(home);
  const [editing, setEditing] = React.useState(false);
  const [tab, setTab] = React.useState('overview');
  React.useEffect(() => { setData(home); setTab('overview'); }, [home]);

  const h = data;
  const buyers = D.interestedIn(h.name);
  const tabs = [
    { id: 'overview', label: 'Overview' },
    { id: 'floorplan', label: 'Floor plan', count: (h.rooms || []).length },
    { id: 'buyers', label: 'Interested buyers', count: buyers.length },
    { id: 'activity', label: 'Activity' },
  ];

  return (
    <div data-screen-label="11 Home Detail">
      <div className="page-head">
        <div>
          <div style={{display:'flex', alignItems:'center', gap: 10, marginBottom: 8}}>
            <span className="eyebrow" style={{cursor:'pointer'}} onClick={onBack}>← HOMES</span>
            <span style={{color:'var(--subtle)'}}>/</span>
            <span className="eyebrow accent">{h.type.toUpperCase()} · PLAN {h.plan}</span>
          </div>
          <div style={{display:'flex', alignItems:'center', gap: 14}}>
            <h1 className="page-title" style={{margin: 0}}>{h.name}</h1>
            {statusPill(h.status)}
          </div>
          <p className="page-sub" style={{marginTop: 6}}>{h.community} · {h.city}</p>
        </div>
        <div className="page-actions">
          <button className="btn ghost sm">{NIcon.share} Share</button>
          <button className="btn ghost sm">{NIcon.download} Brochure</button>
          <button className="btn navy sm">{NI.sparkle} Match to buyer</button>
          <button className="btn" onClick={() => setEditing(true)}>{NIcon.pencil} Edit home</button>
        </div>
      </div>

      {/* Gallery hero */}
      <div className="detail-hero" style={{marginBottom: 22}}>
        <div className="detail-hero-main" style={h.photo ? {backgroundImage: 'url("' + h.photo + '")', backgroundSize: 'cover', backgroundPosition: 'center'} : undefined}>
          {!h.photo && <div className="sky"/>}
          {h.photo && <div className="photo-grade"></div>}
          <div className={'ribbon' + (h.status === 'Summer' ? ' summer' : '')}>{h.status === 'Summer' ? 'Stay in Summer' : h.status}</div>
          <div className="detail-hero-price">{h.price}</div>
          {!h.photo && <span className="detail-hero-tag">Home Rendering · {h.name}</span>}
          <span className="detail-photocount">1 / 12 photos</span>
        </div>
        <div className="detail-thumbs">
          {[
            { t: 'Exterior', p: h.photo },
            { t: 'Street view', p: 'assets/home-craftsman.jpg' },
            { t: 'Curb appeal', p: 'assets/home-blue.jpg' },
            { t: 'Front elevation', p: 'assets/home-brick.jpg' },
            { t: 'Lanai', p: null },
          ].map(th => (
            <div className="detail-thumb" key={th.t} style={th.p ? {backgroundImage: 'url("' + th.p + '")', backgroundSize: 'cover', backgroundPosition: 'center'} : undefined}>
              <span className={th.p ? 'on-photo' : ''}>{th.t}</span>
            </div>
          ))}
        </div>
      </div>

      <div className="lead-layout">
        {/* Key facts */}
        <div className="card profile-card">
          <div className="eyebrow accent" style={{marginBottom: 6}}>PRICED AT</div>
          <div style={{fontFamily:'var(--serif)', fontSize: 34, fontWeight: 600, color:'var(--ink)', lineHeight: 1}}>{h.price}</div>
          <div style={{marginTop: 12}}>{statusPill(h.status)}</div>

          <div className="spec-strip">
            <div className="spec"><div className="spec-v">{h.bed}</div><div className="spec-l">Bed</div></div>
            <div className="spec"><div className="spec-v">{h.bath}</div><div className="spec-l">Bath</div></div>
            <div className="spec"><div className="spec-v">{h.garage}</div><div className="spec-l">Garage</div></div>
            <div className="spec"><div className="spec-v">{h.story}</div><div className="spec-l">Story</div></div>
          </div>
          <div style={{textAlign:'center', fontFamily:'var(--mono)', fontSize: 13, color:'var(--orange)', fontWeight: 600, marginTop: 12}}>{h.sqft} SQ FT</div>

          <div className="profile-grid">
            <div className="profile-row"><div className="lbl">PLAN</div><div className="val mono">{h.plan}</div></div>
            <div className="profile-row"><div className="lbl">HOMESITE</div><div className="val">{h.lot}</div></div>
            <div className="profile-row"><div className="lbl">ORIENTATION</div><div className="val">{h.orientation}</div></div>
            <div className="profile-row"><div className="lbl">HOA</div><div className="val">{h.hoa}</div></div>
            <div className="profile-row"><div className="lbl">COMPLETION</div><div className="val">{h.completion}</div></div>
            <div className="profile-row"><div className="lbl">COMMUNITY</div><div className="val"><span className="link-accent" onClick={() => onSelectCommunity && onSelectCommunity(D.communities.find(c => c.name === h.community))}>{h.community} →</span></div></div>
            <div className="profile-row"><div className="lbl">COUNSELOR</div><div className="val"><div className="av-row"><div className="av" style={{background:'var(--navy)', width: 22, height: 22, fontSize: 9}}>JC</div>Jasmine Carter</div></div></div>
          </div>

          <div className="incentive-box">
            <div className="eyebrow accent" style={{marginBottom: 6}}>★ CURRENT INCENTIVE</div>
            <div style={{fontSize: 13, color:'var(--ink)', fontWeight: 600, lineHeight: 1.45}}>{h.incentive}</div>
          </div>
        </div>

        {/* Main */}
        <div>
          <div className="card insight-strip" style={{marginBottom: 18, background: 'linear-gradient(90deg, var(--orange-soft), transparent 70%)', borderColor: 'var(--orange-line)'}}>
            <div className="ai-bug" style={{width: 32, height: 32, flexShrink: 0}}>{NI.sparkle}</div>
            <div style={{flex: 1, fontSize: 13, lineHeight: 1.55, color:'var(--text)'}}>
              <strong>{h.match}% match</strong> for David &amp; Karen Lin. This home has <strong>{h.leads} active leads</strong> and <strong>{h.views.toLocaleString()} views</strong> on nealcommunities.com this month.
            </div>
            <button className="btn sm">Send to a buyer</button>
          </div>

          <div className="card">
            <div className="tabs" style={{padding: '0 18px'}}>
              {tabs.map(t => (
                <div key={t.id} className={'tab ' + (tab === t.id ? 'active' : '')} onClick={() => setTab(t.id)}>
                  {t.label}{t.count !== undefined && <span className="mono" style={{marginLeft: 6, color:'var(--muted)', fontSize: 11}}>{t.count}</span>}
                </div>
              ))}
            </div>
            <div className="card-body" style={{padding: 22}}>
              {tab === 'overview' && (
                <div>
                  <p style={{fontSize: 14, lineHeight: 1.65, color:'var(--text)', margin: '0 0 20px', maxWidth: 640}}>{h.desc}</p>
                  <div className="eyebrow" style={{marginBottom: 12}}>FEATURES & FINISHES</div>
                  <div style={{display:'flex', flexWrap:'wrap', gap: 8}}>
                    {(h.features || []).map(f => <span className="pill" key={f}>{f}</span>)}
                  </div>
                </div>
              )}
              {tab === 'floorplan' && (
                <div>
                  <div className="eyebrow" style={{marginBottom: 14}}>{NIcon.ruler} ROOM DIMENSIONS · {h.sqft} SQ FT</div>
                  <div className="rooms-grid">
                    {(h.rooms || []).map(r => (
                      <div className="room" key={r.name}>
                        <div className="room-name">{r.name}</div>
                        <div className="room-dim mono">{r.dim}</div>
                      </div>
                    ))}
                  </div>
                  <div className="floorplan-cta">
                    <div style={{fontSize: 13, color:'var(--muted)'}}>Interactive floor plan available on the website.</div>
                    <button className="btn ghost sm">{NIcon.download} Download PDF</button>
                  </div>
                </div>
              )}
              {tab === 'buyers' && (
                <div>
                  <div className="eyebrow" style={{marginBottom: 6}}>{buyers.length} {buyers.length === 1 ? 'BUYER' : 'BUYERS'} INTERESTED IN THIS HOME</div>
                  {buyers.length === 0
                    ? <div style={{color:'var(--muted)', fontSize: 13, marginTop: 10}}>No buyers matched yet. Use “Match to buyer” to surface fits.</div>
                    : buyers.map((b, i) => <InterestedRow key={b.id} b={b} last={i === buyers.length-1} onClick={() => onSelectPerson && b.kind === 'person' && onSelectPerson(b.ref)}/>)}
                </div>
              )}
              {tab === 'activity' && (
                <div className="timeline">
                  {D.homeActivity.map((ev, i) => (
                    <div key={i} className={'event ' + (ev.type === 'ai' ? 'ai' : ev.type === 'orange' ? 'orange' : '')}>
                      <div className="marker"/>
                      <div className="event-head"><span className="event-actor">{ev.actor}</span><span className="event-action">{ev.action}</span><span className="event-time">{ev.time}</span></div>
                      <div className="event-body">{ev.body}</div>
                    </div>
                  ))}
                </div>
              )}
            </div>
          </div>
        </div>
      </div>

      {editing && (
        <NealEditPanel
          title={`${h.name} · ${h.community}`}
          data={h}
          onClose={() => setEditing(false)}
          onSave={setData}
          fields={[
            { key: 'price', label: 'List price' },
            { key: 'status', label: 'Status', type: 'select', options: ['Summer', 'In Progress', 'Move-in Ready', 'Pre-Construction'] },
            { key: 'completion', label: 'Completion / availability' },
            { key: 'incentive', label: 'Current incentive' },
            { key: 'desc', label: 'Description', type: 'textarea' },
          ]}
        />
      )}
    </div>
  );
}

Object.assign(window, { NIcon, NealEditPanel, InterestedRow, NealHomeDetail });

// ═══ COMMUNITY DETAIL ════════════════════════════════════
function NealCommunityDetail({ community, onBack, onSelectHome, onSelectPerson }) {
  const D = window.NealData;
  const [data, setData] = React.useState(community);
  const [editing, setEditing] = React.useState(false);
  const [tab, setTab] = React.useState('overview');
  React.useEffect(() => { setData(community); setTab('overview'); }, [community]);

  const c = data;
  const homes = D.homes.filter(h => h.community === c.name);
  const buyers = D.interestedIn(c.name);
  const tabs = [
    { id: 'overview', label: 'Overview' },
    { id: 'homes', label: 'Available homes', count: c.homes },
    { id: 'buyers', label: 'Buyers', count: c.leads },
    { id: 'activity', label: 'Activity' },
  ];

  return (
    <div data-screen-label="12 Community Detail">
      <div className="page-head">
        <div>
          <div style={{display:'flex', alignItems:'center', gap: 10, marginBottom: 8}}>
            <span className="eyebrow" style={{cursor:'pointer'}} onClick={onBack}>← COMMUNITIES</span>
            <span style={{color:'var(--subtle)'}}>/</span>
            <span className="eyebrow accent">{c.type.toUpperCase()} · EST. {c.established}</span>
          </div>
          <div style={{display:'flex', alignItems:'center', gap: 14}}>
            <h1 className="page-title" style={{margin: 0}}>{c.name}</h1>
            <span className="pill"><span className="dot"/>{c.city}</span>
          </div>
          <p className="page-sub" style={{marginTop: 6}}>{c.tagline}</p>
        </div>
        <div className="page-actions">
          <button className="btn ghost sm">{NIcon.share} Share</button>
          <button className="btn navy sm">{NI.plus} New home</button>
          <button className="btn" onClick={() => setEditing(true)}>{NIcon.pencil} Edit community</button>
        </div>
      </div>

      {/* Aerial hero */}
      <div className="detail-hero" style={{marginBottom: 22}}>
        <div className="detail-hero-main comm" style={c.photo ? {backgroundImage: 'url("' + c.photo + '")', backgroundSize: 'cover', backgroundPosition: 'center 60%'} : undefined}>
          {!c.photo && <div className="comm-sky"/>}
          {c.photo && <div className="photo-grade"></div>}
          <div className="detail-hero-stats">
            <div className="dh-stat"><div className="dh-v">{c.homes}</div><div className="dh-l">Homes available</div></div>
            <div className="dh-stat"><div className="dh-v">{c.from}</div><div className="dh-l">From</div></div>
            <div className="dh-stat"><div className="dh-v">{c.sold}%</div><div className="dh-l">Sold out</div></div>
            <div className="dh-stat"><div className="dh-v">{c.leads}</div><div className="dh-l">Active leads</div></div>
          </div>
          {!c.photo && <span className="detail-hero-tag">Community Aerial · {c.name}</span>}
        </div>
      </div>

      <div className="lead-layout">
        {/* Key facts */}
        <div className="card profile-card">
          <div className="eyebrow accent" style={{marginBottom: 6}}>HOMES FROM</div>
          <div style={{fontFamily:'var(--serif)', fontSize: 34, fontWeight: 600, color:'var(--ink)', lineHeight: 1}}>{c.from}</div>
          <div style={{marginTop: 12, display:'flex', gap: 6, flexWrap:'wrap'}}>
            <span className="pill"><span className="dot"/>{c.type}</span>
            <span className={'pill ' + (c.sold >= 80 ? 'won' : 'warm')}>{c.sold}% sold</span>
          </div>

          <div className="profile-grid">
            <div className="profile-row"><div className="lbl">CITY</div><div className="val">{c.city}</div></div>
            <div className="profile-row"><div className="lbl">ESTABLISHED</div><div className="val">{c.established}</div></div>
            <div className="profile-row"><div className="lbl">ACREAGE</div><div className="val">{c.acres} acres</div></div>
            <div className="profile-row"><div className="lbl">FLOOR PLANS</div><div className="val">{c.plansCount} plans</div></div>
            <div className="profile-row"><div className="lbl">HOA</div><div className="val">{c.hoaRange}</div></div>
            <div className="profile-row"><div className="lbl">PRICE RANGE</div><div className="val mono">{c.priceRange}</div></div>
            <div className="profile-row"><div className="lbl">COUNSELOR</div><div className="val"><div className="av-row"><div className="av" style={{background:'var(--navy)', width: 22, height: 22, fontSize: 9}}>JC</div>Jasmine Carter</div></div></div>
          </div>

          <hr className="div"/>
          <div className="eyebrow" style={{marginBottom: 12}}>AMENITIES</div>
          <div style={{display:'flex', flexWrap:'wrap', gap: 6}}>
            {(c.amenitiesFull || c.amenities).map(a => <span className="pill" key={a}>{a}</span>)}
          </div>
        </div>

        {/* Main */}
        <div>
          <div className="card insight-strip" style={{marginBottom: 18, background: 'linear-gradient(90deg, var(--orange-soft), transparent 70%)', borderColor: 'var(--orange-line)'}}>
            <div className="ai-bug" style={{width: 32, height: 32, flexShrink: 0}}>{NI.sparkle}</div>
            <div style={{flex: 1, fontSize: 13, lineHeight: 1.55, color:'var(--text)'}}>
              <strong>{c.leads} active leads</strong> are tracking {c.name}. Website traffic is up 18% this week from the “Escape the Gray” campaign to northern metros.
            </div>
            <button className="btn sm">{NI.sparkle} Build a journey</button>
          </div>

          <div className="card">
            <div className="tabs" style={{padding: '0 18px'}}>
              {tabs.map(t => (
                <div key={t.id} className={'tab ' + (tab === t.id ? 'active' : '')} onClick={() => setTab(t.id)}>
                  {t.label}{t.count !== undefined && <span className="mono" style={{marginLeft: 6, color:'var(--muted)', fontSize: 11}}>{t.count}</span>}
                </div>
              ))}
            </div>
            <div className="card-body" style={{padding: 22}}>
              {tab === 'overview' && (
                <div>
                  <p style={{fontSize: 14, lineHeight: 1.65, color:'var(--text)', margin: '0 0 20px', maxWidth: 640}}>{c.desc}</p>
                  <div className="eyebrow" style={{marginBottom: 12}}>FULL AMENITY LIST</div>
                  <div style={{display:'flex', flexWrap:'wrap', gap: 8}}>
                    {(c.amenitiesFull || c.amenities).map(a => <span className="pill" key={a}>{a}</span>)}
                  </div>
                </div>
              )}
              {tab === 'homes' && (
                <div>
                  <div className="eyebrow" style={{marginBottom: 14}}>{homes.length} PLANS LISTED IN {c.name.toUpperCase()}</div>
                  <div style={{display:'flex', flexDirection:'column', gap: 12}}>
                    {homes.map(h => (
                      <div key={h.name} className="home-row" onClick={() => onSelectHome && onSelectHome(h)}>
                        <div className="home-row-thumb" style={h.photo ? {backgroundImage: 'url("' + h.photo + '")', backgroundSize: 'cover', backgroundPosition: 'center'} : undefined}>{!h.photo && <div className="sky"/>}</div>
                        <div style={{flex: 1, minWidth: 0}}>
                          <div style={{display:'flex', alignItems:'center', gap: 10}}>
                            <span style={{fontFamily:'var(--serif)', fontSize: 19, fontWeight: 600, color:'var(--ink)'}}>{h.name}</span>
                            {statusPill(h.status)}
                          </div>
                          <div style={{fontSize: 12.5, color:'var(--muted)', marginTop: 4}}>{h.type} · {h.bed} bed · {h.bath} bath · {h.garage} garage · {h.sqft} sq ft</div>
                        </div>
                        <div style={{textAlign:'right'}}>
                          <div style={{fontFamily:'var(--serif)', fontSize: 20, fontWeight: 600, color:'var(--orange)'}}>{h.price}</div>
                          <button className="btn ghost sm" style={{marginTop: 6}}>View {NI.chevron}</button>
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              )}
              {tab === 'buyers' && (
                <div>
                  <div className="eyebrow" style={{marginBottom: 6}}>BUYERS TRACKING {c.name.toUpperCase()}</div>
                  {buyers.length === 0
                    ? <div style={{color:'var(--muted)', fontSize: 13, marginTop: 10}}>No buyers matched to a home here yet.</div>
                    : buyers.map((b, i) => <InterestedRow key={b.id} b={b} last={i === buyers.length-1} onClick={() => onSelectPerson && b.kind === 'person' && onSelectPerson(b.ref)}/>)}
                </div>
              )}
              {tab === 'activity' && (
                <div className="timeline">
                  {D.commActivity.map((ev, i) => (
                    <div key={i} className={'event ' + (ev.type === 'ai' ? 'ai' : ev.type === 'orange' ? 'orange' : '')}>
                      <div className="marker"/>
                      <div className="event-head"><span className="event-actor">{ev.actor}</span><span className="event-action">{ev.action}</span><span className="event-time">{ev.time}</span></div>
                      <div className="event-body">{ev.body}</div>
                    </div>
                  ))}
                </div>
              )}
            </div>
          </div>
        </div>
      </div>

      {editing && (
        <NealEditPanel
          title={`${c.name} · ${c.city}`}
          data={c}
          onClose={() => setEditing(false)}
          onSave={setData}
          fields={[
            { key: 'from', label: 'Starting price' },
            { key: 'priceRange', label: 'Price range' },
            { key: 'established', label: 'Year established' },
            { key: 'tagline', label: 'Tagline' },
            { key: 'desc', label: 'Description', type: 'textarea' },
          ]}
        />
      )}
    </div>
  );
}

Object.assign(window, { NIcon, NealEditPanel, InterestedRow, NealHomeDetail, NealCommunityDetail });
