import React, { useEffect, useRef } from 'react';
import JsBarcode from 'jsbarcode';
import { ArrowRight, ScanLine, ChartNoAxesCombined, Package, Printer } from 'lucide-react';
import { printBarcode } from './barcode.js';
import './demo.css';

export function Barcode({ value }) {
  const ref = useRef(null);
  useEffect(() => { if(value) JsBarcode(ref.current,value,{format:'CODE128',width:2,height:55,margin:14,fontSize:15,displayValue:true}); },[value]);
  return <svg ref={ref} role="img" aria-label={`Scannable barcode ${value}`} />;
}

export function DemoWelcome({ start, busy, error }) {
  return <section className="public-demo" aria-labelledby="demo-title">
    <header><a href="/" aria-label="Stockroom home"><img src="/brand/stockroom-mark.png" alt=""/><strong>stock<span>room</span></strong></a><a href="#signin" onClick={e=>{e.preventDefault();document.getElementById('signin')?.scrollIntoView();document.querySelector('#signin input')?.focus({preventScroll:true});}}>Already exploring? Sign in <ArrowRight size={15}/></a></header>
    <div className="demo-hero-grid"><div>
      <div className="eyebrow">THE STOCKROOM TEST DRIVE</div>
      <h1 id="demo-title">Run the store.<br/><em>Before we meet.</em></h1>
      <p>Scan a delivery. Move it to the shelf. See what sold and what to order next. Try the actual system with a fully stocked fictional store.</p>
      <button className="button" disabled={busy} onClick={()=>start('help')}>{busy?'Opening your store…':'Start interactive demo'} <ArrowRight size={18}/></button>
      <p className="demo-assurance">No email. No card. No sales call. Your own sample workspace.</p>
      {error && <p className="notice error" role="alert">{error}</p>}
      <div className="demo-facts"><span><strong>36</strong> products</span><span><strong>5</strong> locations</span><span><strong>28 days</strong> of sales</span></div>
    </div><div className="demo-report-preview">
      <div className="eyebrow">OAK & FIELD MARKET · SAMPLE REPORT</div><h2>A store you can put to work.</h2>
      <div className="demo-preview-metrics"><div><strong>72</strong><span>stock lots to trace</span></div><div><strong>1,008</strong><span>sample sales records</span></div></div>
      <div className="demo-chart" aria-label="Illustrative sales chart; open reports to explore the workspace data" role="img">{[42,58,47,70,53,80,62,49,77,63,88,73,96,82].map((v,i)=><i key={i} style={{height:v+'%'}}/>)}</div>
      <p>Sample inventory, demand, expiry and purchase reports. Your actions update the workspace records.</p>
      <button className="button secondary" disabled={busy} onClick={()=>start('reports')}>Explore sample reports <ChartNoAxesCombined size={17}/></button>
    </div></div>
    <p><a className="text-link" href="/downloads/">Downloads: server package, practice labels &amp; test guide ↗</a></p>
    <div className="demo-entry-grid">
      <button disabled={busy} onClick={()=>start('receive')}><ScanLine/><h2>Try a scan</h2><p>Use the sample labels with a handheld scanner, type a code, or simulate a scan on screen.</p><span>Open the receiving desk <ArrowRight size={16}/></span></button>
      <button disabled={busy} onClick={()=>start('help')}><Package/><h2>Follow an item</h2><p>Receive, transfer, count, order and reconcile a sale. Explore at your own pace.</p><span>Take the guided test drive <ArrowRight size={16}/></span></button>
      <button disabled={busy} onClick={()=>start('reports')}><ChartNoAxesCombined/><h2>Ask better questions</h2><p>What is on hand? What needs ordering? What expires soon? View and download the answers.</p><span>Open reports <ArrowRight size={16}/></span></button>
    </div>
  </section>;
}

export function DemoShelf({ products, select, onError }) {
  const samples=['SR-1001','SR-1002','SR-1003'].map(s=>products.find(p=>p.sku===s)).filter(Boolean);
  return <section className="panel demo-shelf"><div className="panel-head"><div><div className="eyebrow">YOUR PRACTICE SHELF</div><h2>Pick an item. Try a scan.</h2><p>No scanner needed. Simulate a scan to load the same product a handheld would find.</p></div><ScanLine/></div>
    <div className="demo-shelf-grid">{samples.map(p=><article key={p.id}><span className="tag">{p.category} · per {p.unit}</span><h3>{p.name}</h3><Barcode value={p.barcode}/><p>{p.sku} · {p.stock} {p.unit}s on hand</p><button className="button" onClick={()=>select(p)}>Simulate scan: {p.name}</button><button className="text-link" onClick={()=>{try{printBarcode(p);}catch(e){onError(e.message);}}}><Printer size={15}/> Print practice label</button></article>)}</div>
    <p className="demo-shelf-note">For a physical scanner, print a label or scan it from another screen, focus the barcode field in Receive & scan, and scan with an Enter suffix. This demo uses keyboard-style scanners; camera scanning is not enabled.</p>
  </section>;
}

const hints={
  receive:['Receive 12 cases','Choose a sample item, leave or change the example lot and delivery reference, then confirm the receipt.','Open Inventory to see the extra stock and its movement history.','inventory'],
  inventory:['Inspect the result','Search for Honeycrisp apples and open the product. Review lots, locations and movement history.','Next, move a few cases to another location.','transfers'],
  transfers:['Move 3 units','Create a transfer from a stocked lot to a different location. Enter 3 and save.','The source loses 3, the destination gains 3, and total stock stays the same.','counts'],
  counts:['Resolve a count difference','Open the seeded pending count, review the difference and approve it. You have manager access in this sample store.','The approved variance changes stock and leaves an audit entry.','purchasing'],
  purchasing:['Prepare a supplier order','Draft an order, add a product and quantity, then mark it ordered. You can receive against its remaining quantity.','No supplier email is sent. The order appears in incoming stock.','sales'],
  sales:['Reconcile a sample sale','Choose Use sample sale, preview the rows, then import. Import the same rows again to test duplicate protection.','Stock decreases once; a repeated sale is recognised as a duplicate.','reports'],
  reports:['Read your store reports','Review inventory value and location totals, explore demand and download a CSV. Return after receiving or a sale to compare.','Reports use your fictional workspace records and reflect saved changes.','expiry'],
  expiry:['Find stock that needs attention','Review the upcoming and expired lots. Record waste with a reason against a small quantity.','Stock and waste reporting update together.','help'],
};
export function DemoHint({ page, go }) {
  const h=hints[page]; if(!h)return null;
  return <aside className="demo-hint"><div><strong>TRY THIS · {h[0]}</strong><p>{h[1]}</p><small>What to look for: {h[2]}</small></div><div><button className="text-link" onClick={()=>go(h[3])}>Next: {h[3]==='help'?'demo guide':h[3]} <ArrowRight size={15}/></button><button className="text-link" onClick={()=>go('help')}>All demo activities</button></div></aside>;
}
