/* Artifacts — the triptych: scored segment, campaign log, attribution chart */

function SegmentArtifact() {
  const rows = [
    { id: "c_47812", name: "K. Pereira",   age: "1998 · 26y",  wealth: 92, score: 94, tag: "HVAC · replace" },
    { id: "c_47813", name: "M. Hashimoto", age: "2003 · 21y",  wealth: 88, score: 89, tag: "HVAC · replace" },
    { id: "c_47814", name: "R. Vance",     age: "2009 · 15y",  wealth: 81, score: 76, tag: "HVAC · tune-up" },
    { id: "c_47815", name: "T. Okafor",    age: "1995 · 29y",  wealth: 95, score: 91, tag: "Roof · replace" },
    { id: "c_47816", name: "L. Brennan",   age: "2011 · 13y",  wealth: 73, score: 64, tag: "HVAC · monitor", warn: true },
    { id: "c_47817", name: "D. Castillo",  age: "1992 · 32y",  wealth: 90, score: 88, tag: "HVAC · replace" },
  ];
  return (
    <div className="artifact-frame">
      <div className="artifact-frame-head">
        <div className="left"><span className="dot"></span> segments / HVAC_REPLACE_v3</div>
        <div className="right">
          <span>1,247 matched</span>
          <span>refreshed 02:14 PT</span>
        </div>
      </div>
      <div style={{overflowX:'auto',WebkitOverflowScrolling:'touch'}}>
      <table className="seg-table" style={{minWidth:480}}>
        <thead>
          <tr>
            <th>ID</th><th>Customer</th><th>Home built</th>
            <th className="num">Wealth %ile</th>
            <th className="num">Score</th>
            <th>Tag</th>
          </tr>
        </thead>
        <tbody>
          {rows.map((r, i) => (
            <tr key={i}>
              <td className="id">{r.id}</td>
              <td className="name">{r.name}</td>
              <td>{r.age}</td>
              <td className="num">{r.wealth}</td>
              <td className="num">
                <span className="score-cell" style={{justifyContent:'flex-end'}}>
                  <span className="score-bar"><i style={{width: r.score + '%'}}></i></span>
                  <span className="score-num">{r.score}</span>
                </span>
              </td>
              <td><span className={"pill" + (r.warn ? " warn" : "")}>{r.tag}</span></td>
            </tr>
          ))}
        </tbody>
      </table>
      </div>
      <div className="seg-foot">
        <span>showing 6 of <strong>1,247</strong></span>
        <span>threshold trip at 1,000 → audience build queued</span>
      </div>
    </div>
  );
}

function CampaignLogArtifact() {
  const events = [
    { ts:'02:14 AM', type:'audience', color:'#a78bfa',
      title:'1,247 HVAC replacement candidates identified',
      sub:'Customers with systems 15+ years old · wealth quartile 3 and 4 · scored from your CRM overnight' },
    { ts:'+72 hrs', type:'campaign', color:'#4ade80',
      title:'Campaigns activated across Meta, Yelp, and Google',
      sub:'$420/day · all 3 channels running simultaneously · no manual setup required' },
    { ts:'+72 hrs', type:'shift', color:'#fbbf24',
      title:'14 underperforming zip codes removed automatically',
      sub:'Budget shifted to top-converting areas · CPL target $55 · reallocated without any team involvement' },
    { ts:'Day 3', type:'revenue', color:'#4ade80',
      title:'4 jobs booked · $8,400 in revenue',
      sub:'All 4 traced back to this campaign · CPL tracking at $38 · below target' },
    { ts:'Day 7', type:'revenue', color:'#4ade80',
      title:'11 total jobs booked · $23,100 in revenue',
      sub:'Segment scoring updated overnight · 312 new records added to active audience' },
    { ts:'Day 14', type:'closed', color:'#4ade80',
      title:'$41,200 revenue attributed · 3.1x ROAS · loop closed',
      sub:'Segment refinement queued for next cycle · 3 zip codes added to high-priority list' },
  ];
  return (
    <div className="artifact-frame">
      <div className="artifact-frame-head">
        <div className="left"><span className="dot"></span> activation / business event log</div>
        <div className="right">
          <span>HVAC campaign</span>
          <span>14-day window</span>
        </div>
      </div>
      <div className="camp-log" style={{overflowX:'auto'}}>
        {events.map((e, i) => (
          <div className="row" key={i} style={{borderBottom: i < events.length - 1 ? '1px solid rgba(229,223,208,0.10)' : 'none', paddingBottom:10, marginBottom:10}}>
            <span className="ts" style={{color:'#a8a195', minWidth:64, flexShrink:0}}>{e.ts}</span>
            <span className="level info" style={{color:e.color, flexShrink:0, fontWeight:700, minWidth:64}}>{e.type}</span>
            <span className="msg" style={{flex:1, minWidth:0}}>
              <span style={{display:'block', color:'#1A1814', fontWeight:600, fontSize:13}}>{e.title}</span>
              <span style={{display:'block', color:'#6b6558', fontSize:11.5, marginTop:2, lineHeight:1.45}}>{e.sub}</span>
            </span>
          </div>
        ))}
      </div>
    </div>
  );
}

function AttributionArtifact() {
  // Two simple smooth lines: ad spend (top) vs invoiced revenue (bottom area)
  const W = 720, H = 200, PAD = 12;
  const days = 14;
  // Plausible curves
  const spend = [120, 132, 128, 145, 152, 148, 151, 168, 172, 184, 192, 205, 220, 232]; // $/day in units of $100
  const revenue = [4.2, 4.8, 4.1, 5.4, 6.0, 5.8, 6.4, 7.1, 7.6, 8.4, 9.2, 10.5, 11.8, 13.2]; // $K
  const maxS = Math.max(...spend);
  const maxR = Math.max(...revenue);

  function pathFor(arr, max) {
    const stepX = (W - PAD * 2) / (arr.length - 1);
    const usableH = H - PAD * 2;
    const pts = arr.map((v, i) => [PAD + i * stepX, PAD + usableH - (v / max) * usableH]);
    // smooth via Catmull-Rom-ish
    let d = `M ${pts[0][0]} ${pts[0][1]}`;
    for (let i = 0; i < pts.length - 1; i++) {
      const [x1, y1] = pts[i];
      const [x2, y2] = pts[i + 1];
      const cx = (x1 + x2) / 2;
      d += ` C ${cx} ${y1} ${cx} ${y2} ${x2} ${y2}`;
    }
    return { d, pts };
  }
  const sp = pathFor(spend, maxS);
  const rv = pathFor(revenue, maxR);
  const rvArea = rv.d + ` L ${rv.pts[rv.pts.length-1][0]} ${H - PAD} L ${rv.pts[0][0]} ${H - PAD} Z`;

  return (
    <div className="artifact-frame">
      <div className="artifact-frame-head">
        <div className="left"><span className="dot"></span> attribution / Meta + Yelp + Google → ServiceTitan</div>
        <div className="right">
          <span>14d window</span>
          <span>booked &amp; invoiced</span>
        </div>
      </div>
      <div className="attr">
        <div className="attr-head">
          <div className="left">
            <div className="label">Revenue attributed to paid</div>
            <div className="stat">$112,400 <span className="delta">↑ 38%</span></div>
          </div>
          <div className="right">
            <span><i style={{background:'var(--site-purple)'}}></i> Booked revenue</span>
            <span><i style={{background:'#cdbfff'}}></i> Ad spend</span>
          </div>
        </div>
        <div className="attr-chart-wrap">
          <svg className="attr-chart" viewBox={`0 0 ${W} ${H}`} preserveAspectRatio="none">
            <defs>
              <linearGradient id="rvFill" x1="0" x2="0" y1="0" y2="1">
                <stop offset="0%" stopColor="#4c2fc9" stopOpacity="0.18"/>
                <stop offset="100%" stopColor="#4c2fc9" stopOpacity="0"/>
              </linearGradient>
            </defs>
            {/* gridlines */}
            {[0.25, 0.5, 0.75].map((p) => (
              <line key={p} x1={PAD} x2={W - PAD} y1={PAD + (H - PAD * 2) * p} y2={PAD + (H - PAD * 2) * p} stroke="#E5DFD0" strokeDasharray="2 4" />
            ))}
            {/* spend line (lighter) */}
            <path d={sp.d} fill="none" stroke="#cdbfff" strokeWidth="1.6"/>
            {/* revenue area + line */}
            <path d={rvArea} fill="url(#rvFill)"/>
            <path d={rv.d} fill="none" stroke="#4c2fc9" strokeWidth="2"/>
            {/* end dot */}
            <circle cx={rv.pts[rv.pts.length-1][0]} cy={rv.pts[rv.pts.length-1][1]} r="4" fill="#4c2fc9" stroke="#fff" strokeWidth="2"/>
          </svg>
        </div>
        <div className="attr-axis">
          <span>Apr 21</span>
          <span>Apr 25</span>
          <span>Apr 29</span>
          <span>May 3</span>
        </div>
        <div className="attr-callout">
          <span className="arrow">↳</span>
          <span><strong>−31% CPL</strong> after low-LTV geography suppressed across Yelp · spend held flat, booked revenue lifted <strong>2.4×</strong>.</span>
        </div>
      </div>
    </div>
  );
}

window.SegmentArtifact = SegmentArtifact;
window.CampaignLogArtifact = CampaignLogArtifact;
window.AttributionArtifact = AttributionArtifact;
