// Interactive widgets: SARS rebate calc, ROI, dashboard, testimonials, comparison

// ===================== SARS REBATE CALCULATOR =====================
function SarsRebateCalc(){
  const [litres, setLitres] = React.useState(60000);
  const [dieselPrice, setDieselPrice] = React.useState(23.50);
  // From 1 April 2026, primary sector onland claimants can claim 100% of eligible diesel
  // at up to 366c/L (R3.66/L). Previously they could only claim 80% (≈ R2.928/L).
  const rateNew = 3.66;       // new 100% rate
  const rateOld = rateNew * 0.80; // previous 80% rate (≈ 2.928)
  const rebate = (litres * rateNew);
  const oldRebate = (litres * rateOld);
  const extra = rebate - oldRebate; // the 20% uplift in rand
  const annualSpend = litres * dieselPrice;
  const pct = ((rebate/annualSpend)*100).toFixed(1);

  const priceFmt = (n) => 'R ' + Math.round(n).toLocaleString();

  return (
    <div className="calc-card">
      <div className="calc-head">
        <span className="chip"><span className="dot"></span>Calculator</span>
        <h3 className="calc-title">SARS Diesel Rebate Estimator</h3>
        <p className="calc-sub">See how much SARS owes you back for farm diesel. PompTjom &amp; TenkTjom give you the records you need to claim.</p>
      </div>

      <div className="calc-field">
        <label>Annual farm diesel usage</label>
        <div className="calc-value">{litres.toLocaleString()} <span>litres</span></div>
        <input type="range" min="5000" max="500000" step="1000" value={litres} onChange={e=>setLitres(+e.target.value)} />
        <div className="calc-ticks"><span>5k</span><span>100k</span><span>250k</span><span>500k L</span></div>
      </div>

      <div className="calc-field">
        <label>Your diesel price per litre (R)</label>
        <div className="calc-price-row">
          <div className="calc-value">R{Number(dieselPrice).toFixed(2)}</div>
          <input
            type="number"
            className="calc-price-input"
            min="0" step="0.10"
            value={dieselPrice}
            onChange={e=>setDieselPrice(e.target.value === '' ? 0 : +e.target.value)}
            aria-label="Edit diesel price per litre"
          />
        </div>
        <input type="range" min="15" max="35" step="0.10" value={dieselPrice} onChange={e=>setDieselPrice(+e.target.value)} />
        <div style={{fontSize:11, color:'var(--ink-3)', marginTop:4}}>Type your actual price above, or use the slider.</div>
      </div>

      <div className="calc-result">
        <div className="calc-result-row">
          <span>Annual diesel spend</span>
          <b>{priceFmt(annualSpend)}</b>
        </div>
        <div className="calc-result-row">
          <span>Rebate rate (100% from 1 Apr 2026)</span>
          <b>R {rateNew.toFixed(2)} / L</b>
        </div>
        <div className="calc-result-row big">
          <span>Your estimated annual rebate</span>
          <b className="big-num">{priceFmt(rebate)}</b>
        </div>
        <div className="calc-result-row sub">
          <span>That's {pct}% of your diesel spend back in your pocket.</span>
        </div>

        <div className="calc-uplift">
          <div className="calc-uplift-tag">New from 1 April 2026</div>
          <div className="calc-uplift-grid">
            <div>
              <div className="calc-uplift-label">Old 80% rebate</div>
              <div className="calc-uplift-val muted">{priceFmt(oldRebate)}</div>
              <div className="calc-uplift-sub">@ R {rateOld.toFixed(2)}/L</div>
            </div>
            <div>
              <div className="calc-uplift-label">New 100% rebate</div>
              <div className="calc-uplift-val">{priceFmt(rebate)}</div>
              <div className="calc-uplift-sub">@ R {rateNew.toFixed(2)}/L</div>
            </div>
            <div>
              <div className="calc-uplift-label">Extra in your pocket</div>
              <div className="calc-uplift-val accent">+{priceFmt(extra)}</div>
              <div className="calc-uplift-sub">+20% uplift / yr</div>
            </div>
          </div>
        </div>
      </div>
      <div className="calc-footnote">
        Effective 1 April 2026, SARS allows onland primary-sector claimants to refund 100% of eligible diesel at up to 366c/L — up from 80% previously. Actual rebate depends on eligible usage &amp; documentation. <a href="contact.html">Talk to us</a> to get set up.
      </div>
    </div>
  );
}

// ===================== ROI CALCULATOR =====================
function RoiCalc(){
  const [fleet, setFleet] = React.useState(12);
  const [litresPerMonth, setLitresPerMonth] = React.useState(18000);
  const [price, setPrice] = React.useState(23.50);
  // Industry estimate: smart FMS reduces fuel waste/theft by 8-15%.
  const saving = 0.11;
  const monthlyWaste = litresPerMonth * price;
  const monthlySavings = monthlyWaste * saving;
  const annualSavings = monthlySavings * 12;
  const monthlyFee = fleet * 185 + 650; // illustrative
  const net = annualSavings - (monthlyFee * 12);

  return (
    <div className="calc-card">
      <div className="calc-head">
        <span className="chip"><span className="dot"></span>Calculator</span>
        <h3 className="calc-title">Fuel Savings ROI</h3>
        <p className="calc-sub">Conservative estimate based on an 11% reduction in fuel waste &amp; theft with active monitoring.</p>
      </div>

      <div className="calc-field">
        <label>Vehicles in fleet</label>
        <div className="calc-value">{fleet} <span>vehicles</span></div>
        <input type="range" min="1" max="80" value={fleet} onChange={e=>setFleet(+e.target.value)} />
      </div>
      <div className="calc-field">
        <label>Monthly diesel usage</label>
        <div className="calc-value">{litresPerMonth.toLocaleString()} <span>L / month</span></div>
        <input type="range" min="2000" max="80000" step="500" value={litresPerMonth} onChange={e=>setLitresPerMonth(+e.target.value)} />
      </div>
      <div className="calc-field">
        <label>Diesel price (R/L)</label>
        <div className="calc-value">R{price.toFixed(2)}</div>
        <input type="range" min="18" max="30" step="0.10" value={price} onChange={e=>setPrice(+e.target.value)} />
      </div>

      <div className="calc-result">
        <div className="calc-result-row">
          <span>Monthly fuel spend</span>
          <b>R {Math.round(monthlyWaste).toLocaleString()}</b>
        </div>
        <div className="calc-result-row">
          <span>Estimated monthly savings</span>
          <b>R {Math.round(monthlySavings).toLocaleString()}</b>
        </div>
        <div className="calc-result-row big">
          <span>Projected annual savings</span>
          <b className="big-num">R {Math.round(annualSavings).toLocaleString()}</b>
        </div>
        <div className="calc-result-row sub">
          <span>After PompTjom monthly fee: <b>R {Math.round(net).toLocaleString()}</b> net / year</span>
        </div>
      </div>
      <div className="calc-footnote">
        Studies of telematics-enabled fleets show 8–15% reductions in fuel waste. Your results will vary.
      </div>
    </div>
  );
}

// ===================== LIVE DASHBOARD PREVIEW =====================
// Modelled on the real G5 Agri tank-monitoring dashboard.
function LiveDashboard(){
  const [t, setT] = React.useState(0);
  React.useEffect(()=>{
    const id = setInterval(()=> setT(x=>x+1), 2000);
    return ()=> clearInterval(id);
  }, []);

  // Generate tricolor series: volume (L), liquid level (cm), temperature (°C)
  // Subtle live drift, mostly stable.
  const series = React.useMemo(()=>{
    const N = 60;
    const vol = [], lvl = [], temp = [];
    let v = 39500, l = 258, tp = 14;
    for (let i=0; i<N; i++){
      const drainPhase = Math.sin((i + t*0.05) * 0.22);
      const refill = (i===12 || i===34) ? 3200 : 0;
      v = Math.max(10000, Math.min(42000, v - 120 - drainPhase*60 + refill));
      l = Math.max(80, Math.min(290, l - 0.8 + Math.sin((i+t*0.05)*0.3)*0.6 + (refill?22:0)));
      tp = 12 + Math.sin((i+t*0.03)*0.35)*8 + Math.cos((i+t*0.02)*0.15)*4;
      vol.push(v); lvl.push(l); temp.push(tp);
    }
    return { vol, lvl, temp };
  }, [t]);
  const data = series.vol; // backward compat for any sparkline refs

  const volNow = Math.round(series.vol[series.vol.length-1]);
  const lvlNow = Math.round(series.lvl[series.lvl.length-1]);
  const tempNow = series.temp[series.temp.length-1].toFixed(0);
  const tankCapacity = 42000;
  const pctFull = (volNow / tankCapacity) * 100;
  const ullage = tankCapacity - volNow;
  const dailyUsage = 2429;
  const daysLeft = (volNow / dailyUsage).toFixed(1);

  // Chart dimensions
  const w = 560, h = 180, padL = 36, padR = 10, padT = 14, padB = 22;
  const plotW = w - padL - padR, plotH = h - padT - padB;
  const N = series.vol.length;
  const xStep = plotW / (N - 1);
  const volRange = [8000, 45000];
  const lvlRange = [0, 320];
  const tempRange = [-5, 42];
  const yFor = (v, r) => padT + plotH * (1 - (v - r[0]) / (r[1] - r[0]));
  const mkPath = (arr, r) => arr.map((v,i)=>`${i===0?'M':'L'}${(padL + i*xStep).toFixed(1)},${yFor(v,r).toFixed(1)}`).join(' ');

  return (
    <div className="dash">
      <div className="dash-bar">
        <div className="dash-bar-left">
          <span className="dash-dot"></span>
          <span className="dash-title">Main depot tank · Live</span>
        </div>
        <div className="dash-bar-right">
          <span className="dash-bar-chip">Synced every 4 h · dip every 30 min</span>
          <div className="dash-dots"><span></span><span></span><span></span></div>
        </div>
      </div>

      <div className="dash-body">
        {/* Top row: volume gauge + tricolor chart */}
        <div className="dash-top">
          <div className="dash-gauge-card">
            <div className="dash-card-label red">Volume</div>
            <div className="dash-gauge">
              <div className="dash-gauge-pct">{pctFull.toFixed(1)}%</div>
              <div className="dash-gauge-bar">
                <div className="dash-gauge-fill" style={{height: pctFull + '%'}}>
                  <div className="dash-gauge-lines"></div>
                </div>
                <div className="dash-gauge-scale">
                  <span>100</span>
                  <span>0</span>
                </div>
              </div>
              <div className="dash-gauge-foot">% FULL</div>
            </div>
          </div>

          <div className="dash-chart-card">
            <div className="dash-card-label red">Chart</div>
            <div className="dash-chart-sub">
              <span className="clock-ic">◷</span> Sync every 4 h · dip every 30 min
            </div>
            <svg viewBox={`0 0 ${w} ${h}`} preserveAspectRatio="none" className="dash-chart-svg">
              {/* gridlines */}
              {[0, 0.25, 0.5, 0.75, 1].map((f,i)=>(
                <line key={i} x1={padL} x2={w-padR} y1={padT + plotH*f} y2={padT + plotH*f} stroke="#EFE6D9"/>
              ))}
              {/* left axis labels (volume) */}
              {[45000, 30000, 15000, 0].map((v,i)=>(
                <text key={i} x={padL-6} y={yFor(v, volRange)+3} textAnchor="end" fontSize="8" fill="#B7A990" fontFamily="system-ui">{(v/1000)+'k L'}</text>
              ))}
              {/* series — brand palette */}
              <path d={mkPath(series.temp, tempRange)} fill="none" stroke="#C9A961" strokeWidth="1.6" opacity=".85"/>
              <path d={mkPath(series.lvl, lvlRange)} fill="none" stroke="#1B3A5F" strokeWidth="1.8"/>
              <path d={mkPath(series.vol, volRange)} fill="none" stroke="#8B1E2D" strokeWidth="2.2"/>
              {/* live marker on volume */}
              <circle cx={padL + (N-1)*xStep} cy={yFor(series.vol[N-1], volRange)} r="3.5" fill="#8B1E2D"/>
              <circle cx={padL + (N-1)*xStep} cy={yFor(series.vol[N-1], volRange)} r="8" fill="#8B1E2D" opacity=".3">
                <animate attributeName="r" from="3.5" to="12" dur="1.8s" repeatCount="indefinite"/>
                <animate attributeName="opacity" from=".35" to="0" dur="1.8s" repeatCount="indefinite"/>
              </circle>
            </svg>
            <div className="dash-chart-legend-row">
              <span className="lg"><span className="sw red"></span>Volume</span>
              <span className="lg"><span className="sw navy"></span>Liquid level</span>
              <span className="lg"><span className="sw wheat"></span>Sensor temperature</span>
            </div>
          </div>
        </div>

        {/* KPI strip */}
        <div className="dash-kpis">
          <div className="dash-kpi">
            <div className="dash-kpi-label">Volume</div>
            <div className="dash-kpi-val">{volNow.toLocaleString()} <span>L</span></div>
          </div>
          <div className="dash-kpi">
            <div className="dash-kpi-label">Ullage</div>
            <div className="dash-kpi-val">{ullage.toLocaleString()} <span>L</span></div>
          </div>
          <div className="dash-kpi">
            <div className="dash-kpi-label">Daily usage avg</div>
            <div className="dash-kpi-val">{dailyUsage.toLocaleString()} <span>L</span></div>
          </div>
          <div className="dash-kpi">
            <div className="dash-kpi-label">Days left</div>
            <div className="dash-kpi-val">{daysLeft} <span>days</span></div>
          </div>
          <div className="dash-kpi">
            <div className="dash-kpi-label">Liquid level</div>
            <div className="dash-kpi-val">{lvlNow} <span>cm</span></div>
          </div>
          <div className="dash-kpi">
            <div className="dash-kpi-label">Battery</div>
            <div className="dash-kpi-val">5.9 <span>V</span></div>
          </div>
          <div className="dash-kpi">
            <div className="dash-kpi-label">Sensor temp</div>
            <div className="dash-kpi-val">{tempNow} <span>°C</span></div>
          </div>
        </div>
      </div>
    </div>
  );
}

function SparkLine({ data }){
  const w = 80, h = 28;
  const min = Math.min(...data), max = Math.max(...data);
  const step = w/(data.length-1);
  const path = data.map((v,i)=>`${i===0?'M':'L'}${i*step},${h - ((v-min)/(max-min||1))*h}`).join(' ');
  return <svg viewBox={`0 0 ${w} ${h}`} width={w} height={h}><path d={path} fill="none" stroke="#8B1E2D" strokeWidth="1.5"/></svg>;
}

// ===================== TESTIMONIALS CAROUSEL =====================
function Testimonials(){
  const items = [
    {
      quote: "I lost R14m in stolen fuel in 18 months due to staff reporting false manual dips. TenkTjom is the first time I've actually known what's in my tanks.",
      name: "Owner",
      role: "Diamond miner · Christiana, North West",
      initials: "DM"
    },
    {
      quote: "We used our SARS diesel rebate to fund the whole system. The automated logbooks paid for PompTjom — so the fuel savings on top of that are pure upside.",
      name: "Owner",
      role: "Grain farmer · North West · 2 100 ha",
      initials: "GF"
    },
    {
      quote: "Setup took an afternoon. No drilling, no wiring, no headache. My supervisor reads the app like the weather now.",
      name: "Owner",
      role: "Maize farmer · Free State · 1 400 ha",
      initials: "MF"
    },
    {
      quote: "I was sceptical about 'yet another app'. But being able to see my diesel stock while I'm in Cape Town? Worth it.",
      name: "Owner",
      role: "Mixed farm · Mpumalanga",
      initials: "MF"
    },
  ];
  const [i, setI] = React.useState(0);
  React.useEffect(()=>{
    const id = setInterval(()=> setI(x=>(x+1)%items.length), 7000);
    return ()=> clearInterval(id);
  },[]);
  const t = items[i];
  return (
    <div className="testimonial">
      <div className="testimonial-quote-mark">&ldquo;</div>
      <blockquote key={i} className="testimonial-quote">
        {t.quote}
      </blockquote>
      <div className="testimonial-person">
        <div className="testimonial-avatar">{t.initials || t.name.split(' ').map(n=>n[0]).slice(0,2).join('')}</div>
        <div>
          <div className="testimonial-name">{t.name}</div>
          <div className="testimonial-role">{t.role}</div>
        </div>
      </div>
      <div className="testimonial-dots">
        {items.map((_,k)=>(
          <button key={k} onClick={()=>setI(k)} className={`testimonial-dot ${k===i?'on':''}`} aria-label={`Testimonial ${k+1}`}/>
        ))}
      </div>
    </div>
  );
}

// ===================== PRODUCT COMPARISON =====================
function Compare(){
  const rows = [
    ['What it measures', 'Fuel usage per vehicle, driver, refill', 'Tank level, temperature, flow, location'],
    ['Best for', 'Fleets & farm vehicles in motion', 'Stationary or mobile storage tanks'],
    ['Hardware needed', 'None — app-only', 'IoT sensor (ATEX-certified) per tank'],
    ['Installation', '3–5 days from quote sign-off', '3–5 days from quote sign-off'],
    ['Alerts via', 'App, email, Telegram', 'App, email, Telegram, SMS'],
    ['Logbooks for SARS', 'Automated · Excel export', 'Automated · Excel export'],
    ['Works offline', 'Syncs when online', 'Buffers up to 30 days'],
    ['Monthly fee', 'Request a quote', 'Request a quote'],
  ];
  return (
    <div className="compare">
      <div className="compare-head">
        <div></div>
        <div className="compare-head-cell pomp">
          <span className="compare-logo-mark red"></span>
          <span>PompTjom</span>
        </div>
        <div className="compare-head-cell tenk">
          <span className="compare-logo-mark navy"></span>
          <span>TenkTjom</span>
        </div>
      </div>
      {rows.map((r,i)=>(
        <div key={i} className="compare-row">
          <div className="compare-label">{r[0]}</div>
          <div className="compare-cell">{r[1]}</div>
          <div className="compare-cell">{r[2]}</div>
        </div>
      ))}
      <div className="compare-row compare-cta-row">
        <div></div>
        <div className="compare-cell"><a href="contact.html" className="btn btn-primary" style={{padding:'10px 16px', fontSize:12}}>Get PompTjom →</a></div>
        <div className="compare-cell"><a href="contact.html" className="btn btn-navy" style={{padding:'10px 16px', fontSize:12}}>Get TenkTjom →</a></div>
      </div>
    </div>
  );
}

Object.assign(window, { SarsRebateCalc, RoiCalc, LiveDashboard, Testimonials, Compare });
