/* global React, ReactDOM */
// Shared compare-page template. The HTML wrapper sets window.COMPARE_SLUG before render.

const { useState } = React;
const { PageShell, COMPETITORS, bfUrl } = window.Promptive;

function pillarTypeAndValue(raw) {
  // Map raw pillar cell to {type, value} for visual treatment
  // types: 'check', 'dash', 'text'
  if (raw === '—' || raw == null || raw === '') return { type: 'dash', value: '—' };
  if (typeof raw === 'string' && raw.trim() === '✓') return { type: 'check', value: '✓' };
  return { type: 'text', value: raw };
}

function Cell({ raw, tone }) {
  const { type, value } = pillarTypeAndValue(raw);
  if (type === 'dash') {
    return <span className={`cmp-cell cmp-cell-dash ${tone}`} aria-label="not supported">—</span>;
  }
  if (type === 'check') {
    return <span className={`cmp-cell cmp-cell-check ${tone}`} aria-label="included">✓</span>;
  }
  // text
  const hasCheck = typeof value === 'string' && value.includes('✓');
  return (
    <span className={`cmp-cell cmp-cell-text ${tone} ${hasCheck ? 'has-check' : ''}`}>
      {typeof value === 'string'
        ? value.split(/(✓)/).map((part, i) =>
            part === '✓'
              ? <b key={i} className="cmp-tick">✓</b>
              : <React.Fragment key={i}>{part}</React.Fragment>
          )
        : value}
    </span>
  );
}

/* A small verdict score per pillar — purely cosmetic, narrative-strong.
 * score: 'win' | 'tie' | 'lose' (from Promptive's POV) */
function verdict(pillarLabel, comp, prom) {
  const a = String(comp).trim();
  const b = String(prom).trim();
  if (a === '—' && b !== '—') return 'win';
  if (b === '—' && a !== '—') return 'lose';
  if (a === b) return 'tie';
  // money: lower is better only for "Starting price" where the label is starter money
  if (/price/i.test(pillarLabel)) {
    const num = s => {
      const m = String(s).match(/([\d,]+)/);
      return m ? parseInt(m[1].replace(/,/g, ''), 10) : Infinity;
    };
    return num(b) < num(a) ? 'win' : num(b) > num(a) ? 'lose' : 'tie';
  }
  if (/time to value/i.test(pillarLabel)) {
    // prompive's "< 15 minutes" is the win
    if (/</.test(b) || /min/i.test(b)) return 'win';
    return 'lose';
  }
  // default: promptive wins when its cell contains ✓ and comp doesn't, or is richer text
  if (/✓/.test(b) && !/✓/.test(a)) return 'win';
  if (/✓/.test(a) && !/✓/.test(b)) return 'lose';
  // unknown — call it a qualified win for promptive
  return 'win';
}

function CompareHero({ c }) {
  const wins = c.pillars.filter(p => verdict(p[0], p[1], p[2]) === 'win').length;
  const ties = c.pillars.filter(p => verdict(p[0], p[1], p[2]) === 'tie').length;
  const losses = c.pillars.length - wins - ties;
  return (
    <div className="cmp-hero">
      <div className="cmp-head-row">
        <div className="crumbs">
          <a href="/">Promptive</a> <span>/</span>
          <a href="/promptive-vs-peec">Compare</a> <span>/</span>
          <span>vs {c.name}</span>
        </div>
        <div className="cmp-rightbits">
          <span className="cmp-updated">// reviewed {c.reviewed || 'April 2026'} · {c.pillars.length} criteria</span>
        </div>
      </div>

      <div className="cmp-vs">
        <div className="cmp-party cmp-party-us">
          <div className="cmp-sigil">
            <div className="mark" style={{overflow:'hidden', background:'#F08A2B', display:'flex', alignItems:'center', justifyContent:'center'}}>
              <img src="/images/logo-icon.png" alt="Promptive" width={28} height={28}
                style={{objectFit:'contain', display:'block'}}
                onError={e => { e.target.style.display='none'; }}/>
            </div>
            <div>
              <div className="cmp-pn">Promptive</div>
              <div className="cmp-pt">The team-sport version of the spreadsheet you outgrew.</div>
            </div>
          </div>
        </div>
        <div className="cmp-vsword">
          <div className="vs">VS</div>
          <div className="vsnum">{wins}<small>/{c.pillars.length}</small></div>
          <div className="vslbl">wins · {ties} tie{ties!==1?'s':''} · {losses} loss{losses!==1?'es':''}</div>
        </div>
        <div className="cmp-party cmp-party-them">
          <div className="cmp-sigil cmp-sigil-them" style={{'--them': c.color}}>
            <div className="mark them" style={{overflow:'hidden', background: c.domain ? 'white' : c.color, display:'flex', alignItems:'center', justifyContent:'center'}}>
              {c.domain
                ? <img src={bfUrl(c.domain)} alt={c.name} width={28} height={28}
                    style={{objectFit:'contain', display:'block'}}
                    onError={e => { e.target.style.display='none'; e.target.insertAdjacentHTML('afterend', `<span style="color:white;font-weight:700">${c.sigil}</span>`); }}/>
                : <span style={{color:'white', fontWeight:700}}>{c.sigil}</span>}
            </div>
            <div>
              <div className="cmp-pn">{c.name}</div>
              <div className="cmp-pt">{c.tagline}</div>
            </div>
          </div>
        </div>
      </div>

      <div className="cmp-tldr">
        <div className="eyebrow">// TL;DR</div>
        <p>{c.tldr}</p>
      </div>
    </div>
  );
}

function CompareTable({ c }) {
  return (
    <div className="cmp-table">
      <div className="cmp-row cmp-row-head">
        <div className="cmp-col cmp-col-lbl">Criterion</div>
        <div className="cmp-col cmp-col-them" style={{'--them': c.color}}>
          <span className="cmp-hcell">
            <span className="cmp-chip" style={{background: c.domain ? 'white' : c.color, padding: c.domain ? 2 : 0, display:'inline-flex', alignItems:'center', justifyContent:'center', overflow:'hidden'}}>
              {c.domain
                ? <img src={bfUrl(c.domain)} alt={c.name} width={18} height={18}
                    style={{objectFit:'contain', display:'block'}}
                    onError={e => { e.target.style.display='none'; e.target.insertAdjacentHTML('afterend', `<span style="color:white;font-weight:700;font-size:11px">${c.sigil}</span>`); e.target.parentNode.style.background=c.color; }}/>
                : c.sigil}
            </span>
            {c.name}
          </span>
        </div>
        <div className="cmp-col cmp-col-us">
          <span className="cmp-hcell cmp-hcell-us"><span className="cmp-chip cmp-chip-us"/>Promptive</span>
        </div>
        <div className="cmp-col cmp-col-verdict">Verdict</div>
      </div>
      {c.pillars.map(([lbl, a, b], i) => {
        const v = verdict(lbl, a, b);
        return (
          <div key={lbl} className={`cmp-row cmp-row-${v}`}>
            <div className="cmp-col cmp-col-lbl"><span className="cmp-idx">{String(i+1).padStart(2,'0')}</span>{lbl}</div>
            <div className="cmp-col cmp-col-them"><Cell raw={a} tone={v==='lose' ? 'tone-win' : v==='tie' ? 'tone-tie' : 'tone-lose'}/></div>
            <div className="cmp-col cmp-col-us"><Cell raw={b} tone={v==='win' ? 'tone-win' : v==='tie' ? 'tone-tie' : 'tone-lose'}/></div>
            <div className="cmp-col cmp-col-verdict">
              {v === 'win' && <span className="cmp-v cmp-v-win">Promptive</span>}
              {v === 'tie' && <span className="cmp-v cmp-v-tie">Tie</span>}
              {v === 'lose' && <span className="cmp-v cmp-v-lose">{c.name}</span>}
            </div>
          </div>
        );
      })}
    </div>
  );
}

function MigrateBand({ c }) {
  return (
    <div className="cmp-migrate">
      <div className="cmp-migrate-inner">
        <div className="eyebrow" style={{color:'var(--orange)'}}>// switching from {c.name}?</div>
        <h3>We'll move your data for you.</h3>
        <p>Free migration from {c.name} on any annual plan — prompt sets, tracked competitors, and 90 days of historical data. A solutions engineer does it; you approve. Most migrations finish in under 48 hours.</p>
        <div className="cmp-migrate-btns">
          <a className="btn" href="/signup">Start free trial →</a>
          <a className="btn ghost" href="" onClick={(e) => { e.preventDefault(); window.Calendly?.initPopupWidget({url:'https://calendly.com/getpromptive/promptive-platform-demo'}); }}>Get a demo</a>
        </div>
      </div>
      <ul className="cmp-migrate-steps">
        <li><span>01</span><div><b>Export from {c.name}</b><em>CSV or API — we'll send you a one-liner to run.</em></div></li>
        <li><span>02</span><div><b>Schema match</b><em>We diff field-for-field and flag anything {c.name} doesn't track.</em></div></li>
        <li><span>03</span><div><b>Backfill</b><em>90 days of history imported + re-sampled on our four engines.</em></div></li>
        <li><span>04</span><div><b>Approve &amp; go live</b><em>You review the first report side-by-side. Kill switch if anything's off.</em></div></li>
      </ul>
    </div>
  );
}

function SwitcherQuote({ c }) {
  const q = c.quote || {
    who: '[Head of Content]',
    role: `[Company redacted] · switched from ${c.name}`,
    text: `${c.name} gave us one report a week — and not much in between. With Promptive we see movements the same afternoon we ship a rewrite.`,
    avatar: 'HC'
  };
  return (
    <div className="cmp-quote">
      <div className="cmp-quote-bars">
        <i/><i/><i/><i/><i/>
      </div>
      <blockquote>"{q.text}"</blockquote>
      <div className="cmp-quote-who">
        <span className="av">{q.avatar}</span>
        <div><b>{q.who}</b><em>{q.role}</em></div>
      </div>
    </div>
  );
}

function OtherCompares({ current }) {
  const others = COMPETITORS.filter(x => x.slug !== current);
  return (
    <div className="cmp-others">
      <div className="eyebrow" style={{color:'var(--dim)'}}>// evaluating more tools?</div>
      <h3>Other side-by-sides.</h3>
      <div className="cmp-others-grid">
        {others.map(o => (
          <a key={o.slug} href={o.url || `/promptive-vs-${o.slug}`} className="cmp-other-card">
            <span className="cmp-other-sigil" style={{background: o.domain ? 'white' : o.color, overflow:'hidden', display:'inline-flex', alignItems:'center', justifyContent:'center', padding: o.domain ? 4 : 0}}>
              {o.domain
                ? <img src={bfUrl(o.domain)} alt={o.name} width={22} height={22}
                    style={{objectFit:'contain', display:'block'}}
                    onError={e => { e.target.style.display='none'; e.target.insertAdjacentHTML('afterend', `<span style="font-weight:700;font-size:13px">${o.sigil}</span>`); }}/>
                : o.sigil}
            </span>
            <div>
              <b>vs {o.name}</b>
              <em>{o.tagline}</em>
            </div>
            <span className="cmp-other-arr">→</span>
          </a>
        ))}
      </div>
    </div>
  );
}

function ComparePage() {
  const slug = window.COMPARE_SLUG;
  const c = COMPETITORS.find(x => x.slug === slug);
  if (!c) {
    return <PageShell active="compare"><div className="wrap" style={{padding:80}}>No competitor data for "{slug}".</div></PageShell>;
  }
  return (
    <PageShell active="compare">
      <div className="wrap">
        <CompareHero c={c}/>
      </div>
      <div className="wrap page-body">
        <div className="cmp-table-wrap"><CompareTable c={c}/></div>
        <SwitcherQuote c={c}/>
        <MigrateBand c={c}/>
        <OtherCompares current={c.slug}/>
      </div>
    </PageShell>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<ComparePage/>);
