const {useState, useEffect, useRef, useId} = React;
const {media, brands, accounts, date, metrics, youtubeTypeLabels, makeRealBrandEntries} = Demo;
const format = n => (n == null || Number.isNaN(n)) ? '—' : Number(n).toLocaleString('ja-JP');
const formatSec = sec => {
  if (sec == null || Number.isNaN(sec)) return '—';
  const s = Math.max(0, Math.round(sec));
  const m = Math.floor(s / 60);
  const r = s % 60;
  return m > 0 ? `${m}分${String(r).padStart(2, '0')}秒` : `${r}秒`;
};
const shortDate = d => d ? d.slice(5).replace('-', '/') : '';
const paths = {
  grid:<><rect x="3" y="3" width="7" height="7" rx="1.5"/><rect x="14" y="3" width="7" height="7" rx="1.5"/><rect x="3" y="14" width="7" height="7" rx="1.5"/><rect x="14" y="14" width="7" height="7" rx="1.5"/></>,
  link:<><path d="m10 13 4-4m-5 7-1.3 1.3a3.8 3.8 0 0 1-5.4-5.4L7 8a3.8 3.8 0 0 1 5.3 0m.7-.2 2-2a3.8 3.8 0 0 1 5.4 5.4l-3.7 3.7a3.8 3.8 0 0 1-5.3 0"/></>,
  refresh:<><path d="M20 4v5h-5M4 20v-5h5"/><path d="M4.5 9a8 8 0 0 1 13.8-4L20 9M4 15l1.7 4a8 8 0 0 0 13.8-4"/></>,
  chevron:<path d="m9 6 6 6-6 6"/>, down:<path d="m6 9 6 6 6-6"/>,
  calendar:<><rect x="3" y="5" width="18" height="16" rx="2"/><path d="M7 3v4m10-4v4M3 10h18"/></>,
  brand:<><path d="m12 3 9 5-9 5-9-5 9-5Zm-9 9 9 5 9-5M3 16l9 5 9-5"/></>,
  flask:<><path d="M9 3h6m-5 0v6L4 18q-1 3 2 3h12q3 0 2-3L14 9V3M7 15h10"/></>,
  chart:<><path d="M3 17l5-6 4 3 8-9m-5 0h5v5"/></>,
  pie:<><path d="M10 3a9 9 0 1 0 11 11H10Z"/><path d="M14 2v8h8a9 9 0 0 0-8-8Z"/></>,
  posts:<><rect x="4" y="3" width="16" height="18" rx="2"/><path d="M8 8h8m-8 4h8m-8 4h5"/></>,
  menu:<path d="M3 6h18M3 12h18M3 18h18"/>, close:<path d="m5 5 14 14M19 5 5 19"/>,
  clock:<><circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/></>,
  check:<path d="m4 12 5 5L20 6"/>, alert:<><circle cx="12" cy="12" r="9"/><path d="M12 7v6m0 3h.01"/></>,
  sort:<><path d="M6 5v14m-3-3 3 3 3-3m4-10h8m-8 5h6m-6 5h4"/></>,
  compass:<><circle cx="12" cy="12" r="9"/><path d="m16.2 7.8-2 6.3-6.4 2.1 2-6.3z"/></>,
  layers:<><path d="m12 2 9 4.5-9 4.5-9-4.5Z"/><path d="m3 12 9 4.5 9-4.5"/><path d="m3 17.5 9 4.5 9-4.5"/></>,
  eye:<><path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7-10-7-10-7Z"/><circle cx="12" cy="12" r="3"/></>
};
function Icon({name,size=18}) {
  return <svg aria-hidden="true" width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round">{paths[name]}</svg>;
}
const markLetters={instagram:'IG',tiktok:'TT',youtube:'YT',x:'X'};
function Mark({m,small=false}) {
  return <span className={'mark '+m.id+(small?' small':'')} aria-hidden="true">{markLetters[m.id]}</span>;
}
function Delta({n,unit=''}) {
  if (n == null || Number.isNaN(n)) return null;
  return <span className={'delta '+(n<0?'minus':'')}><span aria-hidden="true">{n<0?'▼':'▲'}</span> {n<0?'−':'+'}{format(Math.abs(n))}{unit}</span>;
}
function DeltaPct({pct,label='前期間比'}) {
  if (pct == null || Number.isNaN(pct)) return null;
  return <div className="delta-row"><span className={'delta '+(pct<0?'minus':'')}><span aria-hidden="true">{pct<0?'▼':'▲'}</span> {pct<0?'−':'+'}{Math.abs(pct).toFixed(1)}%</span><span>{label}</span></div>;
}
function SectionTitle({icon,children}) {
  return <h2 className="section-title"><span className="section-icon"><Icon name={icon} size={17}/></span>{children}</h2>;
}
function SelectBox({label,value,onChange,children,icon}) {
  return <div className="select-box">{icon && <Icon name={icon} size={16}/>}<select aria-label={label} value={value} onChange={e=>onChange(e.target.value)}>{children}</select><Icon name="down" size={13}/></div>;
}
function RefreshButton({action,busy,disabled=false,primary=false}) {
  return <button type="button" className={'btn '+(primary?'primary':'')+(busy?' busy':'')} disabled={disabled||busy} onClick={action}><Icon name="refresh" size={15}/>{busy?'更新中…':'再取得'}</button>;
}
function LineChart({series,days,dates,unit='人',mini=false}) {
  const ref=useRef(null);
  const [width,setWidth]=useState(480);
  const [hover,setHover]=useState(null);
  const id=useId().replace(/:/g,'');
  useEffect(()=>{
    const observer=new ResizeObserver(([entry])=>setWidth(Math.max(50,entry.contentRect.width)));
    observer.observe(ref.current);return ()=>observer.disconnect();
  },[]);
  if (!series || !series.length) return <p className="empty-note">表示できるデータがありません。</p>;
  const len = series.length;
  const h=mini?34:174, left=mini?1:54, right=mini?2:10, top=mini?4:10, bottom=h-(mini?3:24);
  const low=Math.min(...series),high=Math.max(...series),span=Math.max(1,high-low);
  const rough=span/3, power=10**Math.floor(Math.log10(rough));
  const step=([1,2,2.5,5,10].find(v=>v>=rough/power)||10)*power;
  const floor=mini?low:Math.floor(low/step)*step, ceiling=mini?low+span:Math.ceil((high===low?high+1:high)/step)*step;
  const denom = Math.max(1, len - 1);
  const x=i=>left+i/denom*(width-left-right);
  const y=v=>bottom-(v-floor)/Math.max(1e-9,ceiling-floor)*(bottom-top);
  const line=series.map((v,i)=>(i?'L':'M')+x(i).toFixed(2)+' '+y(v).toFixed(2)).join(' ');
  const ticks=mini?[]:Array.from({length:Math.min(6,Math.round((ceiling-floor)/step)+1)},(_,i)=>floor+i*step);
  const current=hover==null?null:Math.min(hover,len-1);
  const labelAt = i => (dates && dates[i]) ? shortDate(dates[i]) : shortDate(date(1 - len + i));
  return <div className={mini?'spark':'line-chart'} ref={ref} onPointerLeave={()=>setHover(null)}>
    <svg width="100%" height={h} viewBox={'0 0 '+width+' '+h} role={mini?undefined:'img'} aria-hidden={mini||undefined} aria-label={mini?undefined:'期間内の推移。初日 '+format(series[0])+unit+'、最終日 '+format(series.at(-1))+unit}
      onPointerMove={mini?undefined:e=>setHover(Math.max(0,Math.min(len-1,Math.round((e.clientX-e.currentTarget.getBoundingClientRect().left-left)/(width-left-right)*denom))))}>
      <defs><linearGradient id={id} x1="0" x2="0" y1="0" y2="1"><stop offset="0%" stopColor="var(--key-400)" stopOpacity={mini?'.24':'.42'}/><stop offset="100%" stopColor="var(--key-200)" stopOpacity=".06"/></linearGradient></defs>
      {ticks.map(v=><g key={v}><line x1={left} x2={width-right} y1={y(v)} y2={y(v)} stroke="var(--line)" strokeDasharray="3 4"/><text x={left-8} y={y(v)+4} textAnchor="end">{format(v)}</text></g>)}
      <path d={line+' L'+x(len-1)+' '+bottom+' L'+left+' '+bottom+' Z'} fill={'url(#'+id+')'}/>
      <path d={line} fill="none" stroke={mini?'var(--key-600)':'var(--primary)'} strokeWidth={mini?1.8:2.6} strokeLinejoin="round"/>
      {!mini && [0,.25,.5,.75,1].map(f=>{const i=Math.round(f*denom);return <text key={f} x={x(i)} y={h-3} textAnchor={f===0?'start':f===1?'end':'middle'}>{labelAt(i)}</text>})}
      {!mini && <circle cx={x(len-1)} cy={y(series.at(-1))} r="3.5" fill="var(--primary)"/>}
      {!mini && current!=null && <g><line x1={x(current)} x2={x(current)} y1={top} y2={bottom} stroke="var(--key-400)" strokeDasharray="3 3"/><circle cx={x(current)} cy={y(series[current])} r="4" fill="var(--primary)"/></g>}
    </svg>
    {!mini && current!=null && <span className="chart-tip" style={{left:Math.min(Math.max(0,x(current)-68),width-158)}}>{labelAt(current)}　{format(series[current])} {unit}</span>}
  </div>;
}
function RetentionChart({curve,title}) {
  const ref = useRef(null);
  const [width, setWidth] = useState(460);
  const [hover, setHover] = useState(null);
  const id = useId().replace(/:/g, '');
  useEffect(() => {
    if (!ref.current) return;
    const observer = new ResizeObserver(([entry]) => setWidth(Math.max(120, entry.contentRect.width)));
    observer.observe(ref.current);
    return () => observer.disconnect();
  }, []);
  if (!curve || !curve.length) {
    return <p className="empty-note">視聴維持率カーブは再生数が一定以上の動画で取得できます。</p>;
  }
  const h = 158, left = 44, right = 12, top = 12, bottom = h - 24;
  const maxVal = Math.max(1, ...curve.map(p => p.watch_ratio));
  const ceiling = maxVal > 1.02 ? Math.ceil(maxVal * 10) / 10 : 1.0;
  const x = r => left + r * (width - left - right);
  const y = v => bottom - (v / ceiling) * (bottom - top);
  const line = curve.map((p, i) => (i ? 'L' : 'M') + x(p.ratio).toFixed(2) + ' ' + y(p.watch_ratio).toFixed(2)).join(' ');
  const ticks = [0, 0.25, 0.5, 0.75, 1.0];
  const cur = hover == null ? null : curve[Math.min(hover, curve.length - 1)];
  return <div className="line-chart retention-chart" ref={ref} onPointerLeave={() => setHover(null)}>
    <svg width="100%" height={h} viewBox={`0 0 ${width} ${h}`} role="img" aria-label={(title || '動画') + 'の視聴維持率カーブ'}
      onPointerMove={e => {
        const rect = e.currentTarget.getBoundingClientRect();
        const frac = Math.max(0, Math.min(1, (e.clientX - rect.left - left) / Math.max(1, width - left - right)));
        setHover(Math.round(frac * (curve.length - 1)));
      }}>
      <defs><linearGradient id={id} x1="0" x2="0" y1="0" y2="1"><stop offset="0%" stopColor="var(--key-600)" stopOpacity=".28"/><stop offset="100%" stopColor="var(--key-200)" stopOpacity=".04"/></linearGradient></defs>
      {ticks.map(v => <g key={v}><line x1={left} x2={width - right} y1={y(v)} y2={y(v)} stroke="var(--line)" strokeDasharray="3 4"/><text x={left - 8} y={y(v) + 4} textAnchor="end">{Math.round(v * 100)}%</text></g>)}
      <path d={`${line} L${x(curve.at(-1).ratio)} ${bottom} L${x(curve[0].ratio)} ${bottom} Z`} fill={`url(#${id})`}/>
      <path d={line} fill="none" stroke="var(--primary)" strokeWidth="2.4" strokeLinejoin="round"/>
      {[0, 0.25, 0.5, 0.75, 1].map(f => <text key={f} x={x(f)} y={h - 4} textAnchor={f === 0 ? 'start' : f === 1 ? 'end' : 'middle'}>{Math.round(f * 100)}%</text>)}
      {cur && <g><line x1={x(cur.ratio)} x2={x(cur.ratio)} y1={top} y2={bottom} stroke="var(--key-400)" strokeDasharray="3 3"/><circle cx={x(cur.ratio)} cy={y(cur.watch_ratio)} r="4" fill="var(--primary)"/></g>}
    </svg>
    {cur && <span className="chart-tip" style={{left: Math.min(Math.max(0, x(cur.ratio) - 70), width - 165)}}>再生 {Math.round(cur.ratio * 100)}% 時点　維持率 {(cur.watch_ratio * 100).toFixed(1)}%</span>}
  </div>;
}
