// Neal Communities — Journeys list (weather hero) + Journey builder/detail + Email preview

// ─── Shared: the designed Neal email preview ─────────────
function NealEmailPreview({ emailId, compact }) {
  const e = window.NealData.emails[emailId];
  if (!e) return null;
  const featHome = (window.NealData.homes || []).find(h => h.name === e.feature.name);
  return (
    <div className={'email-frame' + (compact ? ' compact' : '')}>
      <div className="email-chrome">
        <span className="email-dot" style={{background:'#e0584f'}}/>
        <span className="email-dot" style={{background:'#e6b13e'}}/>
        <span className="email-dot" style={{background:'#3fae6f'}}/>
        <span className="email-from">Neal Communities &lt;hello@nealcommunities.com&gt;</span>
      </div>
      <div className="email-subjbar">
        <div className="email-subj">{e.subject}</div>
        <div className="email-pre">{e.preheader}</div>
      </div>
      <div className="email-body">
        <div className="email-logo">NEAL<span> COMMUNITIES</span></div>
        <div className="email-hero" style={featHome ? {backgroundImage: 'url("' + featHome.photo + '")', backgroundSize: 'cover', backgroundPosition: 'center 60%'} : undefined}>
          {!featHome && <div className="email-hero-sky"></div>}
          {!featHome && <div className="email-hero-sun"></div>}
          <span>NEAL COMMUNITIES · SOUTHWEST FLORIDA</span>
        </div>
        <h2 className="email-headline">{e.headline}</h2>
        <p className="email-p">{e.intro}</p>
        <p className="email-p">{e.body}</p>
        <div className="email-feature">
          <div className="email-feature-thumb" style={featHome ? {backgroundImage: 'url("' + featHome.photo + '")', backgroundSize: 'cover', backgroundPosition: 'center'} : undefined}></div>
          <div style={{flex: 1}}>
            <div className="email-feature-name">{e.feature.name}</div>
            <div className="email-feature-meta">{e.feature.meta}</div>
            <div className="email-feature-spec">{e.feature.spec}</div>
          </div>
        </div>
        <div className="email-cta">{e.cta}</div>
        <div className="email-sign">{e.signoff}</div>
      </div>
    </div>
  );
}

// ═══ JOURNEYS LIST (compact weather signal + recipe cards) ═
const TRIGGER_LABELS = { weather: 'Weather', location: 'Location', lifecycle: 'Lifecycle', inventory: 'Inventory', behavior: 'Behavior' };

function NealJourneys({ onOpenJourney }) {
  const d = window.NealData;
  const w = d.weather;
  const triggeringNow = w.north.filter(c => c.trigger).reduce((s, c) => s + c.people, 0);
  const activeCount = d.journeys.filter(j => j.status === 'active').length;

  return (
    <div data-screen-label="09 Journeys">
      <div className="page-head">
        <div>
          <div className="eyebrow accent" style={{marginBottom: 8}}>{d.journeys.length} JOURNEYS · {activeCount} ACTIVE</div>
          <h1 className="page-title">Customer Journeys</h1>
          <p className="page-sub">Automations that reach the right people at the right moment — triggered by what buyers do, where they are in the journey, your inventory, and even the weather.</p>
        </div>
        <div className="page-actions">
          <button className="btn ghost">{NI.sparkle} Suggest a journey</button>
          <button className="btn">{NI.plus} New journey</button>
        </div>
      </div>

      {/* Compact live-signal strip */}
      <div className="card wx-strip" style={{marginBottom: 22}}>
        <div className="wx-strip-main">
          <span className="wxchip wx-sun sm">{WX.sunny}<span className="mono">{w.florida.temp}°</span><span className="wxchip-cond">{w.florida.city}</span></span>
          <span style={{fontSize: 12.5, color:'var(--text)'}}><strong>{triggeringNow} contacts</strong> are in weather-trigger conditions right now</span>
        </div>
        <div className="wx-strip-cities">
          {w.north.filter(c => c.trigger).map(c => (
            <span className={'wxchip sm ' + wxClass(c.tag)} key={c.city}>{WX[c.tag]}<span className="mono">{c.temp}°</span><span className="wxchip-cond">{c.city.split(',')[0]}</span></span>
          ))}
        </div>
      </div>

      {/* RECIPE CARDS */}
      <div className="eyebrow" style={{marginBottom: 14}}>JOURNEYS — WHEN THIS HAPPENS, SEND THIS</div>
      <div style={{display:'flex', flexDirection:'column', gap: 16}}>
        {d.journeys.map(j => {
          const em = d.emails[j.email];
          return (
            <div className="card recipe-card" key={j.id} onClick={() => onOpenJourney(j.id)}>
              <div className="recipe-head">
                <div style={{display:'flex', alignItems:'center', gap: 12}}>
                  <div className={'recipe-ic ' + wxClass(j.trigger.icon)}>{WX[j.trigger.icon] || WX.pin}</div>
                  <div>
                    <div style={{display:'flex', alignItems:'center', gap: 10}}>
                      <span className="recipe-name">{j.name}</span>
                      <span className={'pill ' + (j.status === 'active' ? 'won' : j.status === 'paused' ? 'warm' : '')} style={{fontSize: 10.5}}><span className="dot"/>{j.status === 'active' ? 'Active' : j.status === 'paused' ? 'Paused' : 'Draft'}</span>
                      <span className="pill" style={{fontSize: 10.5}}>{TRIGGER_LABELS[j.trigger.type] || j.trigger.type}</span>
                    </div>
                    <div className="recipe-tag">{j.tagline}</div>
                  </div>
                </div>
                <label className="switch" onClick={(ev) => ev.stopPropagation()}>
                  <input type="checkbox" defaultChecked={j.status === 'active'}/>
                  <span className="track"/>
                </label>
              </div>

              <div className="recipe-flow">
                <div className="recipe-step">
                  <div className="recipe-step-lbl">WHEN THIS HAPPENS</div>
                  <div className="recipe-step-body">{j.trigger.summary}</div>
                </div>
                <div className="recipe-conn">→</div>
                <div className="recipe-step">
                  <div className="recipe-step-lbl">TO THESE PEOPLE</div>
                  <div className="recipe-step-body"><strong className="mono" style={{color:'var(--orange)'}}>{j.audience.count}</strong> · {j.audience.summary}</div>
                </div>
                <div className="recipe-conn">→</div>
                <div className="recipe-step">
                  <div className="recipe-step-lbl">SEND THIS</div>
                  <div className="recipe-step-body">“{em.subject}”</div>
                </div>
              </div>

              <div className="recipe-foot">
                <div className="recipe-metric"><span className="mono">{j.metrics.sent.toLocaleString()}</span> sent</div>
                <div className="recipe-metric"><span className="mono" style={{color:'var(--good)'}}>{j.metrics.openRate}%</span> open rate</div>
                <div className="recipe-metric"><span className="mono">{j.metrics.toured}</span> toured</div>
                <div className="recipe-metric"><span className="mono" style={{color:'var(--orange)'}}>{j.metrics.reserved}</span> reserved</div>
                <button className="btn ghost sm" style={{marginLeft:'auto'}} onClick={(ev) => { ev.stopPropagation(); onOpenJourney(j.id); }}>Open journey {NI.chevron}</button>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

// ═══ JOURNEY DETAIL / BUILDER ════════════════════════════
function NealJourneyDetail({ journey, onBack, onSelectPerson }) {
  const d = window.NealData;
  const j = journey;
  const em = d.emails[j.email];
  const enrolledPeople = d.people.filter(p => p.journeys.includes(j.id));

  return (
    <div data-screen-label="10 Journey">
      <div className="page-head">
        <div>
          <div style={{display:'flex', alignItems:'center', gap: 10, marginBottom: 8}}>
            <span className="eyebrow" style={{cursor:'pointer'}} onClick={onBack}>← JOURNEYS</span>
            <span style={{color:'var(--subtle)'}}>/</span>
            <span className="eyebrow accent">{(TRIGGER_LABELS[j.trigger.type] || j.trigger.type).toUpperCase() + '-TRIGGERED'}</span>
          </div>
          <div style={{display:'flex', alignItems:'center', gap: 14}}>
            <h1 className="page-title" style={{margin: 0}}>{j.name}</h1>
            <span className={'pill ' + (j.status === 'active' ? 'won' : j.status === 'paused' ? 'warm' : '')}><span className="dot"/>{j.status === 'active' ? 'Active' : j.status === 'paused' ? 'Paused' : 'Draft'}</span>
          </div>
          <p className="page-sub" style={{marginTop: 6}}>{j.tagline}</p>
        </div>
        <div className="page-actions">
          <button className="btn ghost sm">Duplicate</button>
          <button className="btn ghost sm">{j.status === 'active' ? 'Pause' : 'Activate'}</button>
          <label className="switch" style={{margin: '0 4px'}}>
            <input type="checkbox" defaultChecked={j.status === 'active'}/>
            <span className="track"/>
          </label>
          <button className="btn">Save changes</button>
        </div>
      </div>

      {/* AI assist */}
      <div className="card insight-strip" style={{marginBottom: 22, 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>The assistant built this journey.</strong> It wrote the email copy, set the trigger rule, and picked the audience. {j.metrics.openRate}% open rate is <strong>{j.metrics.openRate - 24} pts above</strong> your account average — the personalized subject line is doing the work.
        </div>
        <button className="btn sm">{NI.sparkle} Tune with AI</button>
      </div>

      <div className="journey-layout">
        {/* LEFT — the recipe */}
        <div style={{display:'flex', flexDirection:'column', gap: 0}}>

          {/* WHEN */}
          <div className="build-step">
            <div className="build-badge">1</div>
            <div className="card build-card">
              <div className="build-head">
                <div className={'recipe-ic ' + wxClass(j.trigger.icon)} style={{width: 36, height: 36}}>{WX[j.trigger.icon] || WX.pin}</div>
                <div>
                  <div className="eyebrow accent">WHEN THIS HAPPENS</div>
                  <div className="build-title">{j.trigger.summary}</div>
                </div>
                <button className="btn ghost sm" style={{marginLeft:'auto'}}>Edit trigger</button>
              </div>
              <div className="build-body">
                <div className="cond-list">
                  {j.trigger.conditions.map((c, i) => (
                    <div className="cond" key={i}><span className="cond-op">{i === 0 ? 'IF' : 'AND'}</span>{c}</div>
                  ))}
                </div>
                {j.trigger.type === 'weather' && (
                  <div className="build-note">{NI.sparkle} Neal checks the forecast for every contact’s home city each morning at 7am local time.</div>
                )}
              </div>
            </div>
          </div>
          <div className="build-spine">↓</div>

          {/* WHO */}
          <div className="build-step">
            <div className="build-badge">2</div>
            <div className="card build-card">
              <div className="build-head">
                <div className="recipe-ic wx-cloud" style={{width: 36, height: 36, background:'var(--navy)', color:'#fff'}}>
                  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" width="17" height="17"><path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M22 21v-2a4 4 0 0 0-3-3.87"/></svg>
                </div>
                <div>
                  <div className="eyebrow accent">TO THESE PEOPLE</div>
                  <div className="build-title"><span className="mono" style={{color:'var(--orange)', fontWeight: 700}}>{j.audience.count}</span> people match · {j.audience.summary}</div>
                </div>
                <button className="btn ghost sm" style={{marginLeft:'auto'}}>Edit audience</button>
              </div>
              <div className="build-body">
                <div style={{display:'flex', gap: 6, flexWrap:'wrap', marginBottom: 14}}>
                  {j.audience.filters.map((f, i) => <span className="pill" key={i}>{f}</span>)}
                </div>
                <div className="eyebrow" style={{marginBottom: 10}}>SAMPLE OF WHO’S ENROLLED</div>
                <div style={{display:'flex', flexDirection:'column', gap: 0}}>
                  {enrolledPeople.slice(0, 4).map((p, i) => (
                    <div key={p.id} onClick={() => onSelectPerson && onSelectPerson(p)} className="enroll-mini" style={{borderBottom: i < Math.min(enrolledPeople.length,4)-1 ? '1px solid var(--border)' : 0}}>
                      <div className="av" style={{background: p.color, width: 26, height: 26, fontSize: 10}}>{p.initials}</div>
                      <div style={{flex: 1, minWidth: 0}}>
                        <div className="av-name" style={{fontSize: 12.5}}>{p.name}</div>
                        <div className="av-meta" style={{fontSize: 11}}>{p.city}, {p.state}</div>
                      </div>
                      <WxChip wx={p.wx} sm/>
                    </div>
                  ))}
                </div>
                {enrolledPeople.length > 4 && <div style={{marginTop: 10}}><button className="btn ghost sm">View all {j.audience.count} enrolled</button></div>}
              </div>
            </div>
          </div>
          <div className="build-spine">↓</div>

          {/* SEND */}
          <div className="build-step">
            <div className="build-badge">3</div>
            <div className="card build-card">
              <div className="build-head">
                <div className="recipe-ic" style={{width: 36, height: 36, background:'var(--orange)', color:'#fff'}}>{NI.send}</div>
                <div>
                  <div className="eyebrow accent">SEND THIS EMAIL</div>
                  <div className="build-title">{em.headline}</div>
                </div>
                <button className="btn ghost sm" style={{marginLeft:'auto'}}>{NI.sparkle} Rewrite</button>
              </div>
              <div className="build-body" style={{display:'grid', gridTemplateColumns:'1fr', gap: 0}}>
                <NealEmailPreview emailId={j.email}/>
              </div>
            </div>
          </div>
        </div>

        {/* RIGHT — results */}
        <div style={{display:'flex', flexDirection:'column', gap: 16, position:'sticky', top: 0}}>
          <div className="card">
            <div className="card-head"><div className="card-title">Results</div><span className="pill orange" style={{fontSize: 10.5}}>{NI.sparkle} Last 30 days</span></div>
            <div className="card-body">
              <div className="result-grid">
                <div className="result-cell"><div className="result-v">{j.metrics.sent.toLocaleString()}</div><div className="result-l">Emails sent</div></div>
                <div className="result-cell"><div className="result-v" style={{color:'var(--good)'}}>{j.metrics.openRate}%</div><div className="result-l">Open rate</div></div>
                <div className="result-cell"><div className="result-v">{j.metrics.clicked}</div><div className="result-l">Clicked</div></div>
                <div className="result-cell"><div className="result-v" style={{color:'var(--orange)'}}>{j.metrics.reserved}</div><div className="result-l">Reserved</div></div>
              </div>
              <NSparkline data={j.metrics.spark} color="var(--orange)"/>
              <div style={{fontSize: 11, color:'var(--muted)', textAlign:'center', marginTop: 6}}>Engaged contacts, trailing 14 weeks</div>
            </div>
          </div>

          <div className="card">
            <div className="card-head"><div className="card-title">Journey funnel</div></div>
            <div className="card-body">
              {j.metrics.funnel.map((row, i) => (
                <div className="funnel-row" key={row.label} style={{gridTemplateColumns:'92px 1fr 48px 48px'}}>
                  <div className="funnel-stage" style={{fontSize: 12}}>{row.label}</div>
                  <div className="funnel-bar"><div className="funnel-fill" style={{width: row.pct + '%', background: i >= 4 ? 'linear-gradient(90deg, var(--orange), var(--orange-hi))' : undefined}}/></div>
                  <div className="funnel-cnt">{row.v}</div>
                  <div className="funnel-pct">{row.pct}%</div>
                </div>
              ))}
            </div>
          </div>

          <div className="card insight-strip" style={{flexDirection:'column', alignItems:'flex-start', gap: 10}}>
            <div className="eyebrow accent">{NI.sparkle} ASSISTANT NOTE</div>
            <div style={{fontSize: 12.5, lineHeight: 1.55, color:'var(--text)'}}>
              7 contacts in this journey have toured but not reserved. Want me to draft a follow-up with this week’s incentive and a homesite that backs the preserve?
            </div>
            <button className="btn sm">Draft follow-up</button>
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { NealEmailPreview, NealJourneys, NealJourneyDetail });
