/* global React, LITIO */
const { useState: uS } = React;
const T = window.T;
function NF(){ return new Intl.NumberFormat(window.CURLANG==='en'?'en-US':'es-AR'); }
const usd = (v) => 'US$ ' + NF().format(Math.round(v));
const MES_ES = ['ene','feb','mar','abr','may','jun','jul','ago','sep','oct','nov','dic'];
const MES_EN = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
const NEWS_DATE = (s) => { const [y,m,d]=s.split('-'); const M=window.CURLANG==='en'?MES_EN:MES_ES; return d+' '+M[+m-1]+' '+y; };

/* ---------- small SVG helpers ---------- */
function Donut({ data, size=140, thickness=22 }){
  const r=(size-thickness)/2, c=2*Math.PI*r, cx=size/2;
  const total=data.reduce((a,d)=>a+d.pct,0); let acc=0;
  return (
    <svg width={size} height={size} style={{flex:'0 0 auto'}}>
      <circle cx={cx} cy={cx} r={r} fill="none" stroke="#E5EBED" strokeWidth={thickness}/>
      {data.map((d,i)=>{
        const len=d.pct/total*c, off=-acc; acc+=len;
        return <circle key={i} cx={cx} cy={cx} r={r} fill="none" stroke={d.color}
          strokeWidth={thickness} strokeDasharray={`${len} ${c-len}`} strokeDashoffset={off}
          transform={`rotate(-90 ${cx} ${cx})`}/>;
      })}
      <text x={cx} y={cx-4} textAnchor="middle" style={{fontFamily:'var(--font-display)',fontWeight:700,fontSize:'27px',fill:'#16242B'}}>{data[0].pct}%</text>
      <text x={cx} y={cx+15} textAnchor="middle" style={{fontFamily:'var(--font-mono)',fontSize:'9px',letterSpacing:'.1em',fill:'#869198'}}>{T('prod.donutsub')}</text>
    </svg>
  );
}
function Spark({ series, n=28, color='#1C7C8B', w=78, h=30 }){
  const d=series.data.slice(-n).map(p=>p.c);
  const mn=Math.min(...d), mx=Math.max(...d);
  const pts=d.map((v,i)=>`${(i/(d.length-1))*w},${h-((v-mn)/(mx-mn||1))*h}`).join(' ');
  return (
    <svg className="spark" viewBox={`0 0 ${w} ${h}`} preserveAspectRatio="none">
      <polyline points={pts} fill="none" stroke={color} strokeWidth="1.8" strokeLinejoin="round"/>
    </svg>
  );
}

function LiLogo({ id }){
  return (
    <svg className="logo" viewBox="0 0 36 36" fill="none">
      <defs>
        <linearGradient id={id} x1="3" y1="3" x2="33" y2="33" gradientUnits="userSpaceOnUse">
          <stop offset="0" stopColor="#F5F8F9"/>
          <stop offset="0.5" stopColor="#CFD8DC"/>
          <stop offset="1" stopColor="#9DAAB0"/>
        </linearGradient>
      </defs>
      <rect x="1.5" y="1.5" width="33" height="33" rx="9" fill={`url(#${id})`} stroke="#1C7C8B" strokeWidth="1.5"/>
      <text x="18" y="18" textAnchor="middle" dominantBaseline="central" fontFamily="'Source Serif 4', Georgia, serif" fontWeight="700" fontSize="19" fill="#21323A">Li</text>
    </svg>
  );
}

/* ================= NAV ================= */
function Nav({ lang, onLang }){
  const links=['precios','produccion','proyectos','rigi','noticias','blog','glosario'];
  return (
    <nav className="nav">
      <div className="container">
        <a href="#top" className="brand">
          <LiLogo id="liTileNav"/>
          <span className="brand-name">Litio<b>Hoy</b></span>
        </a>
        <div className="nav-links">
          {links.map(h=><a key={h} href={'#'+h}>{T('nav.'+h)}</a>)}
        </div>
        <div className="nav-right">
          <div className="lang-switch" role="group" aria-label="Idioma">
            <button className={lang==='es'?'on':''} onClick={()=>onLang('es')}>ES</button>
            <button className={lang==='en'?'on':''} onClick={()=>onLang('en')}>EN</button>
          </div>
          <div className="nav-cta"><span className="dot"></span>{T('nav.live')}</div>
        </div>
      </div>
    </nav>
  );
}

/* ================= TICKER ================= */
function Ticker(){
  const s=LITIO.snap;
  const items=[
    {l:T('tk.carb'), v:usd(s.carb.v)+'/t', c:s.carb.chg},
    {l:T('tk.prod'), v:T('tk.prodv'), c:75},
    {l:T('tk.res'), v:T('tk.resv'), c:null},
    {l:T('tk.inv'), v:T('tk.invv'), c:null}
  ];
  const Row=({arr})=> arr.map((it,i)=>(
    <span className="tk" key={i}>
      <span className="lbl">{it.l}</span><span className="val">{it.v}</span>
      {it.c!=null && <span className={'chg '+(it.c>=0?'up':'down')}>{it.c>=0?'▲':'▼'}{Math.abs(it.c).toFixed(it.c%1===0?0:1)}%</span>}
    </span>
  ));
  return (
    <div className="ticker">
      <div className="ticker-track"><Row arr={items}/><Row arr={items}/></div>
    </div>
  );
}

/* ================= HERO ================= */
function Hero(){
  const s=LITIO.snap;
  return (
    <section id="top" className="hero">
      <div className="hero-grid"></div>
      <div className="container">
        <div className="hero-inner">
          <div>
            <div className="eyebrow">{T('hero.ey')}</div>
            <h1>{T('hero.h_pre')}<span className="hl">{T('hero.h_hl')}</span>{T('hero.h_post')}</h1>
            <p className="lede">{T('hero.lede')}</p>
            <div className="hero-actions">
              <a href="#precios" className="btn btn-ghost">{T('hero.btn1')}</a>
              <a href="#proyectos" className="btn btn-ghost">{T('hero.btn2')}</a>
            </div>
          </div>
          <div className="hero-metrics">
            <div className="hm feat">
              <div className="k">{T('hm.prod')}</div>
              <div className="v">{NF().format(130800)} <small>{T('hm.lce')}</small></div>
              <div className="d up">{T('hm.prod_d')}</div>
            </div>
            <div className="hm">
              <div className="k">{T('hm.carb')}</div>
              <div className="v" style={{fontSize:'23px'}}>{usd(s.carb.v)}<small>/t</small></div>
              <div className={'d '+(s.carb.chg>=0?'up':'down')}>{s.carb.chg>=0?'▲':'▼'} {Math.abs(s.carb.chg).toFixed(1)}%</div>
              <Spark series={LITIO.SERIES.carb} color="#1C7C8B"/>
            </div>
            <div className="hm">
              <div className="k">{T('hm.rigi')}</div>
              <div className="v" style={{fontSize:'23px'}}>US$ {NF().format(4665)}<small>M</small></div>
              <div className="d flat">{T('hm.rigi_d')}</div>
            </div>
            <div className="hm">
              <div className="k">{T('hm.proj')}</div>
              <div className="v" style={{fontSize:'23px'}}>6<small>{T('hm.proj_unit')}</small></div>
              <div className="d flat">{T('hm.proj_d')}</div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ================= PRODUCTION ================= */
function ProductionSection(){
  const P=LITIO.production;
  const maxY=Math.max(...P.years.map(y=>y.t));
  const maxP=Math.max(...P.byProject2025.map(p=>p.t));
  const dec = (n)=> n.toString().replace('.', window.CURLANG==='en'?'.':',');
  return (
    <section id="produccion" className="sec-pad" style={{background:'var(--bg-2)',borderTop:'1px solid var(--line)',borderBottom:'1px solid var(--line)'}}>
      <div className="container">
        <div className="sec-head">
          <div>
            <div className="eyebrow">{T('s.prod.ey')}</div>
            <h2>{T('s.prod.h')}</h2>
            <p>{T('s.prod.p')}</p>
          </div>
        </div>

        <div className="prod-grid">
          <div className="panel prod-bars">
            <h3>{T('prod.bars.h')}</h3>
            <div className="sub">{T('prod.bars.sub')}</div>
            {P.years.map(y=>(
              <div className="barrow" key={y.y}>
                <div className="yr">{y.y}</div>
                <div className="track"><div className={'fill'+(y.est?' est':'')} style={{width:(y.t/maxY*100)+'%'}}></div></div>
                <div className="amt">{NF().format(y.t)}{y.est && <em>{T('prod.est')}</em>}</div>
              </div>
            ))}
          </div>

          <div className="prod-side">
            <div className="panel donut-card">
              <h3>{T('prod.demand.h')}</h3>
              <div className="donut-wrap">
                <Donut data={P.demand}/>
                <div className="donut-legend">
                  {P.demand.map((d,i)=>(
                    <div className="dl-row" key={i}>
                      <span className="dl-sw" style={{background:d.color}}></span>
                      <span className="dl-name">{d.u}</span>
                      <span className="dl-pct">{d.pct}%</span>
                    </div>
                  ))}
                </div>
              </div>
            </div>
            <div className="panel proj-split">
              <h3>{T('prod.split.h')} <span style={{color:'var(--muted-2)',fontFamily:'var(--font-mono)',fontSize:'11px'}}>{T('prod.estparen')}</span></h3>
              {P.byProject2025.map((p,i)=>(
                <div className="split-row" key={i}>
                  <span className="sr-name">{p.name} <span className="sr-prov">{p.prov}</span></span>
                  <span className="sr-bar"><i style={{width:(p.t/maxP*100)+'%',background:p.color}}></i></span>
                  <span className="sr-amt">{NF().format(p.t)}</span>
                </div>
              ))}
            </div>
          </div>
        </div>

        <div className="panel" style={{padding:'24px',marginTop:'22px'}}>
          <h3 style={{fontSize:'16px',marginBottom:'18px'}}>{T('prod.res.h')} <span style={{color:'var(--muted-2)',fontFamily:'var(--font-mono)',fontSize:'11px'}}>{T('prod.res.src')}</span></h3>
          {P.reserves.map((r,i)=>{
            const hl=r.c==='Argentina';
            return (
              <div className="split-row" key={i}>
                <span className="sr-name" style={hl?{color:'var(--lime)',fontWeight:700}:{}}>{r.c}</span>
                <span className="sr-bar" style={{width:'260px'}}><i style={{width:(r.share/31*100)+'%',background:hl?'var(--lime)':'#C4CDD2'}}></i></span>
                <span className="sr-amt">{dec(r.share)}%</span>
              </div>
            );
          })}
        </div>
      </div>
    </section>
  );
}

/* ================= RIGI ================= */
const RSTATUS={apr:{k:'rstatus.apr',c:'op'},eva:{k:'rstatus.eva',c:'adv'},prep:{k:'rstatus.prep',c:'con'},rej:{k:'rstatus.rej',c:'rej'}};
function RigiSection(){
  const R=LITIO.rigi, h=R.headline;
  return (
    <section id="rigi" className="sec-pad">
      <div className="container">
        <div className="sec-head">
          <div>
            <div className="eyebrow">{T('s.rigi.ey')}</div>
            <h2>{T('s.rigi.h')}</h2>
            <p>{T('s.rigi.p')}</p>
          </div>
        </div>

        <div className="rigi-hero">
          <div className="rh"><div className="k">{T('rigi.hp1')}</div><div className="v">US$ {NF().format(h.presentado)}<small>M</small></div><div className="s">{T('rigi.hp1s')}</div></div>
          <div className="rh accent"><div className="k">{T('rigi.hp2')}</div><div className="v">US$ {NF().format(h.litioMonto)}<small>M</small></div><div className="s">{T('rigi.hp2s')}</div></div>
          <div className="rh"><div className="k">{T('rigi.hp3')}</div><div className="v">{h.aprobadoPct}<small>%</small></div><div className="s">{T('rigi.hp3s_a')} {NF().format(h.aprobadoMonto)}M · {h.proyectosAprobados} {T('rigi.hp3s_b')}</div></div>
          <div className="rh"><div className="k">{T('rigi.hp4')}</div><div className="v">US$ {NF().format(h.esperaMonto)}<small>M</small></div><div className="s">{T('rigi.hp4s')}</div></div>
        </div>

        <div className="rigi-cols">
          <div className="panel benefits">
            <h3>{T('rigi.ben.h')}</h3>
            <div className="sub">{T('rigi.ben.sub')}</div>
            {R.benefits.map((b,i)=>(
              <div className="benefit" key={i}>
                <div className="bn">{String(i+1).padStart(2,'0')}</div>
                <div><div className="bt">{b.t}</div><div className="bd">{b.d}</div></div>
              </div>
            ))}
          </div>

          <div className="panel rigi-table">
            <h3>{T('rigi.tbl.h')}</h3>
            <div className="sub">{T('rigi.tbl.sub')}</div>
            <table className="rtbl">
              <thead><tr><th>{T('rigi.th.project')}</th><th>{T('rigi.th.prov')}</th><th className="num">{T('rigi.th.inv')}</th><th>{T('rigi.th.status')}</th></tr></thead>
              <tbody>
                {R.projects.map((p,i)=>{
                  const st=RSTATUS[p.status];
                  return (
                    <tr key={i}>
                      <td><div className="pn">{p.name}</div><div className="cp">{p.company} · {p.date}</div></td>
                      <td className="cp">{p.prov}</td>
                      <td className="num"><span className="inv" style={{whiteSpace:'nowrap'}}>US$&nbsp;{NF().format(p.inv)}M</span></td>
                      <td><span className={'badge '+st.c}><span className="bdot"></span>{T(st.k)}</span></td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
            <div className="rigi-deadline">
              <div className="dl-icon">{R.deadline}</div>
              <div className="dl-txt">{R.deadlineNote}</div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ================= NEWS ================= */
function NewsSection(){
  const allLbl = T('news.all');
  const cats=[allLbl,...Array.from(new Set(LITIO.news.map(n=>n.cat)))];
  const [cat,setCat]=uS(allLbl);
  const active = cats.includes(cat) ? cat : allLbl;
  const list=LITIO.news.filter(n=>active===allLbl||n.cat===active);
  return (
    <section id="noticias" className="sec-pad" style={{background:'var(--bg-2)',borderTop:'1px solid var(--line)',borderBottom:'1px solid var(--line)'}}>
      <div className="container">
        <div className="sec-head">
          <div>
            <div className="eyebrow">{T('s.news.ey')}</div>
            <h2>{T('s.news.h')}</h2>
            <p>{T('s.news.p')}</p>
          </div>
          <div className="news-filters">
            {cats.map(c=>(
              <button key={c} className={'chip'+(active===c?' on':'')} onClick={()=>setCat(c)}
                style={active===c?{color:'#1C7C8B',borderColor:'#1C7C8B',background:'rgba(28,124,139,.1)'}:{}}>{c}</button>
            ))}
          </div>
        </div>
        <div className="news-grid">
          {list.map((n,i)=>(
            <article className={'news-card'+(n.feat?' feat':'')} key={i}>
              <div className="news-meta">
                <span className="news-cat">{n.cat}</span>
                <span className="news-date">{NEWS_DATE(n.date)}</span>
              </div>
              <h3>{n.title}</h3>
              <p>{n.summary}</p>
              <div className="news-src">{T('news.src')} · <b>{n.src}</b></div>
            </article>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ================= GLOSSARY ================= */
function GlossarySection(){
  return (
    <section id="glosario" className="sec-pad">
      <div className="container">
        <div className="sec-head">
          <div>
            <div className="eyebrow">{T('s.gloss.ey')}</div>
            <h2>{T('s.gloss.h')}</h2>
            <p>{T('s.gloss.p')}</p>
          </div>
        </div>
        <dl className="gloss-grid">
          {LITIO.glossary.map((g,i)=>(
            <div className="gloss" key={i}><dt>{g.t}</dt><dd>{g.d}</dd></div>
          ))}
        </dl>

        <div className="method-note">
          <div className="mn-head">
            <div className="eyebrow">{T('method.ey')}</div>
            <h2>{T('method.h')}</h2>
          </div>
          <div>
            <p>{T('method.p')}</p>
            <div className="mn-sources">
              {['SMM','Fastmarkets','USGS','Intratec','CAEM / ILiA','Sec. de Minería','BCR','Reuters'].map(s=>(
                <span key={s}>{s}</span>
              ))}
            </div>
            <div className="mn-updated">{T('method.updated')}{(()=>{const t=new Date();const M=window.CURLANG==='en'?MES_EN:MES_ES;return t.getDate()+' '+M[t.getMonth()]+' '+t.getFullYear();})()}</div>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ================= FOOTER ================= */
function Footer(){
  const navLinks=['precios','produccion','proyectos','rigi'];
  return (
    <footer>
      <div className="container">
        <div className="foot-grid">
          <div>
            <div className="brand" style={{marginBottom:'14px'}}>
              <LiLogo id="liTileFoot"/>
              <span className="brand-name">Litio<b style={{color:'var(--lime)'}}>Hoy</b></span>
            </div>
            <p className="muted" style={{fontSize:'13px',maxWidth:'280px'}}>{T('foot.tag')}</p>
          </div>
          <div><h5>{T('foot.sections')}</h5>{navLinks.map(h=><a key={h} href={'#'+h}>{T('nav.'+h)}</a>)}</div>
          <div><h5>{T('foot.data')}</h5><a href="#noticias">{T('nav.noticias')}</a><a href="#blog">{T('nav.blog')}</a><a href="#glosario">{T('nav.glosario')}</a><a href="#produccion">{T('foot.reserves')}</a></div>
          <div><h5>{T('foot.sources')}</h5><a>SMM · Fastmarkets</a><a>USGS · Intratec</a><a>CAEM · ILiA</a><a>Sec. de Minería · BCR</a></div>
        </div>
        <div className="foot-note">
          <span>{T('foot.note')}</span>
          <span style={{display:'flex',gap:'16px'}}>
            <a href={window.CURLANG==='en'?'/en/privacy/':'/privacidad/'}>{T('foot.privacy')}</a>
            <a href={window.CURLANG==='en'?'/en/terms/':'/terminos/'}>{T('foot.terms')}</a>
          </span>
          <span className="mono">{T('foot.made')}</span>
        </div>
      </div>
    </footer>
  );
}

Object.assign(window,{Nav,Ticker,Hero,ProductionSection,RigiSection,NewsSection,GlossarySection,Footer});
