/* Presentation for published D2C results. Canonical findings and test plans remain unchanged. */
function d2cResearchSelection(segments, selection, contextKey) {
  return segments.find(s => selection?.contextKey === contextKey && s.segmentVersionId === selection.id) || segments[0] || null;
}
function d2cResearchEvidence(dashboard, item) {
  const eligible = new Set(d2cNativeReviews(dashboard).map(r => r.reviewVersionId));
  const ids = new Set(item?.reviewEvidenceIds || []);
  return (dashboard.evidence || []).filter(e => ids.has(e.evidenceId) && eligible.has(e.reviewVersionId));
}
function d2cResearchProductImage(product) {
  const candidate = product?.imageUrl || product?.metadata?.images?.[0]?.url || product?.metadata?.images?.[0];
  const exactEben = product?.id === 'p_70c1ed282f3de3571ea9e7e2fabf3cc0' && product?.canonicalUrl === 'https://undgretel.com/products/eben';
  return exactEben ? {src:'/assets/d2c/0cb38.png',crop:true} : {src:d2cSafeUrl(candidate),crop:false};
}
/* Approved prototype copy is bound to these immutable persona versions. New versions use canonical copy. */
function d2cResearchNeed(segment,lang) {
  const copy={
    'segment-version-104e8747d7f70b61a1654e8f':['Sichtbarer Ausgleich ohne geschminkten Look.','Visible evening of the skin without a made-up look.'],
    'segment-version-d91f09dbf6acce6220891761':['Ein ausgeglichener Teint, der sich angenehm leicht anfühlt.','An even complexion with a comfortably light feel.'],
    'segment-version-8e4e82f713868efe4dd263c4':['Selbst bestimmen, wie viel Abdeckung gerade nötig ist.','Choose how much coverage you need.']
  };
  return copy[segment?.segmentVersionId]?.[lang==='en'?1:0]||d2cText(d2cField(segment,'description',lang),lang).split(/(?<=\.)\s+/)[0];
}
function D2CResearchIcon({file,size=20}) { return <img src={'/assets/d2c/'+file} width={size} height={size} alt="" aria-hidden="true"/>; }
function d2cResearchTone(segment,index) {
  const tones = [{key:'natural',icon:'bb187.svg'},{key:'light',icon:'213a4.svg'},{key:'coverage',icon:'0ba76.svg'}];
  return tones[{'natural-finish':0,'light-feel':1,'buildable-coverage':2}[segment?.personaKey] ?? index % tones.length];
}
function D2CProductHero({dashboard,scope,lang,t}) {
  const products=dashboard.products||[],product=scope.type==='product'?products.find(p=>p.id===scope.id):products.length===1?products[0]:null;
  const image=d2cResearchProductImage(product),m=dashboard.metrics||{};
  return <section className="d2c-product-hero" aria-label={t('productFit')}>
    <div className={'d2c-hero-photo'+(image.crop?' is-eben':'')}>{image.src?<img src={image.src} alt={product?.title||''}/>:<D2CResearchIcon file="0ba76.svg" size={32}/>}</div>
    <div className="d2c-hero-copy"><h1>{product?.title || (lang==='de'?'Shop-Analyse':'Shop analysis')}</h1><p>{product?.title==='EBEN'&&image.crop?'Liquid Foundation · UND GRETEL':product?.metadata?.brand||products.length+' '+t('products')}</p>
      <div className="d2c-hero-metrics"><span><strong>{d2cNumber(m.denominator??m.analysedTextReviews??m.analyzedTextCount,lang)}</strong> {lang==='de'?'Textreviews':'text reviews'}</span><span><strong>{d2cNumber(m.ratingAll?.mean,lang,1)} / 5</strong> {t('rating')} <small>n={d2cNumber(m.ratingAll?.n,lang)}</small></span><span><strong>{(dashboard.segments||[]).filter(s=>(s.metrics?.n??s.metrics?.count??0)>0).length}</strong> {lang==='de'?'Persona-Hypothesen':'persona hypotheses'}</span></div>
    </div>{d2cSafeUrl(product?.canonicalUrl)&&<a className="d2c-button d2c-product-source" href={d2cSafeUrl(product.canonicalUrl)} target="_blank" rel="noopener noreferrer">{lang==='de'?'Produktseite':'Product page'}</a>}
  </section>;
}
function D2CResearchPlan({canonical,segment,dashboard,t,lang,onBack,onEvidence,inReport,onToggle}) {
  const item=d2cLocalized(canonical,lang),parts=d2cActionParts(item,lang),vp=item.validationPlan||{},tone=d2cResearchTone(segment,segment?d2cProfileIndex(segment,dashboard):0);
  return <section className="d2c-plan" data-tone={tone.key}>
    <button className="d2c-button d2c-plan-back" onClick={onBack}>← {lang==='de'?'Zurück zur Auswahl':'Back to selection'}</button>
    <header><D2CResearchIcon file={tone.icon} size={32}/><div><p className="d2c-plan-kicker">{item.priority} · {t('testPlan')}</p><h1>{d2cResultTitle(item,lang)}</h1></div><D2CStatus value={item.status} t={t}/></header>
    <nav className="d2c-plan-steps" aria-label={t('testPlan')}><a href="#d2c-plan-change">1. {lang==='de'?'Was ändern?':'What changes?'}</a><a href="#d2c-plan-proof">2. {lang==='de'?'Proof vorbereiten':'Prepare proof'}</a><a href="#d2c-plan-decision">3. {lang==='de'?'Entscheidung festlegen':'Set decision rule'}</a></nav>
    <section id="d2c-plan-change"><h2>{lang==='de'?'Eine Variable. Ein klarer Vergleich.':'One variable. A clear comparison.'}</h2><div className="d2c-plan-comparison">{parts.control&&<article><p className="d2c-plan-kicker">A · {t('controlLabel')}</p><h3>{lang==='de'?'Bestehendes Creative':'Current creative'}</h3><p>{parts.control}</p></article>}<article className="is-variant"><p className="d2c-plan-kicker">{parts.control?'B · ':''}{t('variantLabel')}</p><h3>{lang==='de'?'Das wird getestet':'What to test'}</h3><p>{parts.variant}</p></article></div>{canonical.actionType==='creative'&&<div className="d2c-plan-constants"><D2CResearchIcon file="ed857.svg" size={22}/><p>{t('nextTestsHint')}</p></div>}</section>
    <div className="d2c-plan-proof"><article id="d2c-plan-proof"><p className="d2c-plan-kicker">2 · {lang==='de'?'Proof & Assets':'Proof & assets'}</p><h2>{lang==='de'?'Das muss sichtbar sein':'What needs to be visible'}</h2>{Array.isArray(vp.assets)?<ul>{vp.assets.map((x,i)=><li key={i}>{d2cText(x,lang)}</li>)}</ul>:<p>{d2cText(vp.assets,lang)}</p>}</article><article id="d2c-plan-decision"><p className="d2c-plan-kicker">3 · {lang==='de'?'Messung & Entscheidung':'Measurement & decision'}</p><h2>{lang==='de'?'Vor dem Start festlegen':'Define before launch'}</h2><p>{d2cText(vp.measurement,lang)}</p></article></div>
    <section className="d2c-plan-hypothesis"><p className="d2c-plan-kicker">{t('hypothesis')}</p><p>{typeof vp==='object'?d2cText(vp.hypothesis,lang):d2cText(vp,lang)}</p></section>
    <section className="d2c-panel"><h2>{t('why')}</h2><p>{d2cText(item.why,lang)}</p><button className="d2c-button" onClick={onEvidence}>{lang==='de'?'Reviewbelege öffnen':'Open review evidence'}</button>{item.requiredInputs?.length>0&&<details><summary>{t('required')}</summary><ul>{item.requiredInputs.map((x,i)=><li key={i}>{d2cText(x,lang)}</li>)}</ul></details>}<details><summary>{t('deliverable')}</summary><p>{d2cText(item.deliverable,lang)}</p></details><details><summary>{t('method')}</summary>{item.knowledgeRuleRefs?.length?item.knowledgeRuleRefs.map((r,i)=><div className="d2c-rule" key={i}><strong>{r.methodId}</strong><p>{d2cText(r.passage||r.rulePassage||r.claim,lang)}</p><small>{r.knowledgeVersion} · {r.sourceHash}</small></div>):<p>{t('notEstablished')}</p>}</details><label className="d2c-report-selection"><input type="checkbox" checked={inReport} onChange={()=>onToggle(item.recommendationId)}/>{t('reportInclude')}</label></section>
  </section>;
}
function D2CResearch({dashboard,scope,contextKey,t,lang,openDetail,page,setPage,selectedReport,toggleReport}) {
  const segments=(dashboard.segments||[]).filter(s=>(s.metrics?.n??s.metrics?.count??0)>0);
  const [selection,setSelection]=React.useState(null),[plan,setPlan]=React.useState(null);
  const selected=d2cResearchSelection(segments,selection,contextKey),index=selected?d2cProfileIndex(selected,dashboard):0,tone=d2cResearchTone(selected,index);
  const finding=(dashboard.findings||[]).find(f=>f.segmentVersionIds?.includes(selected?.segmentVersionId));
  const evidence=d2cResearchEvidence(dashboard,finding),quote=evidence.find(e=>e.polarity==='positive')||evidence[0],negative=evidence.filter(e=>e.polarity==='negative').length;
  const recommendation=(dashboard.recommendations||[]).find(r=>r.segmentVersionIds?.includes(selected?.segmentVersionId)&&['creative','creator_brief','landing_page'].includes(r.actionType));
  const boundPlan=plan?.contextKey===contextKey&&(dashboard.recommendations||[]).find(r=>r.recommendationId===plan.id);
  const openPlan=r=>{setPlan({id:r.recommendationId,contextKey});requestAnimationFrame(()=>document.querySelector('.d2c-plan-back')?.focus());document.querySelector('.d2c-main')?.scrollTo({top:0,behavior:'auto'});};
  const evidenceFor=(segment)=>openDetail({kind:'segment',item:segment,index:segment?d2cProfileIndex(segment,dashboard):0});
  const showRec=r=>openDetail({kind:'recommendation',item:r,selector:{kind:'recommendation',recommendationId:r.recommendationId}});
  const choose=s=>{setSelection({id:s.segmentVersionId,contextKey});setPlan(null);if(window.matchMedia('(max-width:600px)').matches)requestAnimationFrame(()=>document.querySelector('.d2c-persona-preview')?.scrollIntoView({block:'start',behavior:window.matchMedia('(prefers-reduced-motion:reduce)').matches?'auto':'smooth'}));};
  React.useEffect(()=>{setPlan(null);},[page]);
  const actions=(dashboard.recommendations||[]).filter(r=>page==='tests'?['creative','creator_brief','landing_page'].includes(r.actionType):!['creative','creator_brief','landing_page'].includes(r.actionType));
  const labels={personas:'Personas',tests:'Tests',feedback:lang==='de'?'Produktfeedback':'Product feedback',data:lang==='de'?'Datenbasis':'Data quality'};
  return <div className="d2c-research">{!boundPlan&&<><D2CProductHero dashboard={dashboard} scope={scope} lang={lang} t={t}/><div className="d2c-research-tabs" role="tablist" aria-label={lang==='de'?'Ergebnisse':'Results'}>{['personas','tests','feedback'].map(key=><button key={key} role="tab" id={'d2c-tab-'+key} aria-controls="d2c-research-content" aria-selected={page===key} tabIndex={page===key||(page==='data'&&key==='personas')?0:-1} onKeyDown={e=>{const keys=['personas','tests','feedback'];let n=Math.max(0,keys.indexOf(page));if(e.key==='ArrowRight')n=(n+1)%keys.length;else if(e.key==='ArrowLeft')n=(n+keys.length-1)%keys.length;else if(e.key==='Home')n=0;else if(e.key==='End')n=keys.length-1;else return;e.preventDefault();setPage(keys[n]);setPlan(null);document.getElementById('d2c-tab-'+keys[n])?.focus();}} onClick={()=>{setPage(key);setPlan(null);}}>{labels[key]} · {key==='personas'?segments.length:(dashboard.recommendations||[]).filter(r=>key==='tests'?['creative','creator_brief','landing_page'].includes(r.actionType):!['creative','creator_brief','landing_page'].includes(r.actionType)).length}</button>)}</div></>}
  <div id="d2c-research-content" role={page==='data'||boundPlan?undefined:'tabpanel'} aria-labelledby={page==='data'||boundPlan?undefined:'d2c-tab-'+page}>
  {boundPlan?<D2CResearchPlan canonical={boundPlan} segment={segments.find(s=>boundPlan.segmentVersionIds?.includes(s.segmentVersionId))} dashboard={dashboard} lang={lang} t={t} onBack={()=>{setPlan(null);requestAnimationFrame(()=>document.querySelector('[data-d2c-plan-opener="'+boundPlan.recommendationId+'"]')?.focus());}} onEvidence={()=>showRec(boundPlan)} inReport={selectedReport.includes(boundPlan.recommendationId)} onToggle={toggleReport}/>:page==='personas'?<>
    <div id="d2c-segments" className="d2c-personas-heading"><h2>{lang==='de'?'Personas aus den Reviews':'Personas from the reviews'}</h2><p>{lang==='de'?'Wähle ein Kaufmotiv, um die Belege und den passenden Test zu sehen.':'Select a buying motive to see its evidence and the matching test.'}</p></div>
    {segments.length?<><div className="d2c-persona-cards">{segments.map((s,i)=>{const m=s.metrics||{},n=m.count??m.n,denominator=m.denominator??dashboard.metrics?.denominator,share=m.share,active=s.segmentVersionId===selected?.segmentVersionId,style=d2cResearchTone(s,d2cProfileIndex(s,dashboard));const description=d2cResearchNeed(s,lang);return <button type="button" className="d2c-persona-card" data-tone={style.key} aria-pressed={active} key={s.segmentVersionId} onClick={()=>choose(s)}><div className="d2c-card-top"><span className="d2c-motif"><D2CResearchIcon file={style.icon} size={32}/></span><D2CStatus value={m.evidenceStatus||s.evidenceStatus||'insufficient'} t={t}/></div><h3>{d2cText(d2cField(s,'label',lang),lang)}</h3><div className="d2c-card-stat"><div className="d2c-share-ring" style={{'--share':Math.min(100,Math.max(0,(share??0)*100))+'%'}} aria-hidden="true"/><div><strong>{d2cNumber(share==null?null:share*100,lang,1)} %</strong><p>{d2cNumber(n,lang)} / {d2cNumber(denominator,lang)} {lang==='de'?'Textreviews':'text reviews'}</p></div></div><p className="d2c-card-need">{description}</p><div className="d2c-card-footer"><span>{active?(lang==='de'?'Ausgewählte Persona':'Selected persona'):(lang==='de'?'Persona ansehen':'Explore persona')}</span><D2CResearchIcon file="33d3e.svg" size={16}/></div></button>})}</div>
    <p className="d2c-footnote">{lang==='de'?'Anteile beziehen sich auf die aktuelle Textreview-Basis. Personas können sich überschneiden und sind abgeleitete Hypothesen.':'Shares refer to the current text-review base. Personas may overlap and are inferred hypotheses.'}</p>
    <section className="d2c-persona-preview" data-tone={tone.key} aria-live="polite"><div className="d2c-preview-finding"><h3>{d2cText(d2cField(selected,'label',lang),lang)}</h3><p>{d2cResearchNeed(selected,lang)}</p>{quote&&<blockquote><D2CResearchIcon file="6b644.svg" size={20}/><p>„{quote.evidenceQuote}“</p></blockquote>}<div className="d2c-actions"><button className="d2c-button" onClick={()=>evidenceFor(selected)}>{lang==='de'?'Belege ansehen':'View evidence'} · {evidence.length} {t('statements')}</button>{negative>0&&<span className="d2c-counterevidence">{negative} {lang==='de'?'Gegenbelege':'counterevidence statements'}</span>}</div></div><div className="d2c-preview-test"><D2CResearchIcon file="c2ace.svg" size={22}/><h3>{lang==='de'?'Nächster Test':'Next test'}</h3>{recommendation?<><p>{d2cActionParts(recommendation,lang).variant}</p><button className="d2c-button primary" data-d2c-plan-opener={recommendation.recommendationId} onClick={()=>openPlan(recommendation)}>{lang==='de'?'Testplan öffnen':'Open test plan'} <span aria-hidden="true">→</span></button></>:<p>{t('noRecommendations')}</p>}</div></section></>:<div className="d2c-empty"><h2>{t('noProfiles')}</h2><p>{t('noMatchesText')}</p></div>}
  </>:page==='data'?<section className="d2c-research-data"><h2>{labels.data}</h2><D2CCoverage dashboard={dashboard} scopeLabel={scope.type==='shop'?t('allGroups'):scope.type==='product'?(dashboard.products||[]).find(p=>p.id===scope.id)?.title:scope.id} t={t} lang={lang}/>{(dashboard.warnings||[]).map((w,i)=><p className="d2c-data-warning" key={i}>{d2cText(w.message||w,lang)}</p>)}<p className="d2c-footnote">{t('snapshot')}: {dashboard.snapshotId}<br/>{t('knowledge')}: {dashboard.knowledgeVersion}</p></section>:<section><div className="d2c-personas-heading"><h2>{page==='tests'?t('nextTests'):t('feedbackSection')}</h2><p>{page==='tests'?t('nextTestsHint'):t('feedbackIntro')}</p></div><div className="d2c-action-cards">{actions.map(r=><article key={r.recommendationId} className="d2c-action-card"><header><span>{r.priority}</span><D2CStatus value={r.status} t={t}/></header><h3>{d2cResultTitle(r,lang)}</h3><p>{d2cActionParts(r,lang).variant}</p><footer><span>{d2cResearchEvidence(dashboard,r).length} {t('statements')}</span><button className="d2c-button primary" data-d2c-plan-opener={r.recommendationId} onClick={()=>page==='tests'?openPlan(r):showRec(r)}>{page==='tests'?t('testOpen'):t('feedbackOpen')} →</button></footer></article>)}</div>{!actions.length&&<div className="d2c-empty"><p>{t('noRecommendations')}</p></div>}</section>}
  </div>{dashboard.warnings?.length>0&&page!=='data'&&<aside className="d2c-quality-banner"><D2CResearchIcon file="ff32b.svg" size={20}/><p>{d2cText(dashboard.warnings[0].message||dashboard.warnings[0],lang)}</p><button className="d2c-button" onClick={()=>{setPage('data');setPlan(null);}}>{lang==='de'?'Datenbasis ansehen':'View data quality'}</button></aside>}</div>;
}
