import React, { useEffect, useId, useState } from 'react';
import { createRoot } from 'react-dom/client';
import '@fontsource-variable/manrope';
import '@fontsource-variable/dm-sans';
import { ArrowRight, ArrowUpRight, Check, ChevronDown, ChevronLeft, ChevronRight, CircleHelp, ClipboardList, FileText, Grid2X2, Layers, LoaderCircle, Minus, Package, Plus, Ruler, Search, ShieldCheck, ShoppingBag, SlidersHorizontal, Trash2, X, ZoomIn, ZoomOut } from 'lucide-react';
import { money, sumLines, type Product, type Configuration, type Price, type Line, type Identity, type Quote } from '../domain/model';
import './styles.css';
import { Shop, Checkout } from './enterprise/Commercial';
import { DesignLanding, MyParts, Projects } from './enterprise/Parts';
import { OrdersList, OrderDetail, OrderWorkspaceLink } from './enterprise/Orders';
import { MeshConfigurator } from './configurator/MeshConfigurator';
import { MeshThumbnail } from './configurator/MeshViewport';
import { BarConfigurator } from './configurator/BarConfigurator';
import { BarThumbnail } from './configurator/BarViewport';

async function api<T>(path: string, method = 'GET', data?: unknown): Promise<T> {
  const response = await fetch('/api' + path, { method, credentials: 'same-origin', headers: data === undefined ? {} : { 'Content-Type': 'application/json' }, body: data === undefined ? undefined : JSON.stringify(data) });
  const result = await response.json() as T & { error?: string };
  if (!response.ok) throw new Error(result.error ?? 'Request failed.');
  return result as T;
}
const message = (error: unknown) => error instanceof Error ? error.message : 'Something went wrong.';
const familyName = { bar: 'Reinforcing bar', mesh: 'Reinforcing mesh', accessories: 'Supports & accessories', fabrication: 'Custom fabrication' };
const routeFor = (p: Product) => `/configure/${p.family === 'fabrication' ? 'shapes' : p.family}?product=${p.id}`;
function useRoute() {
  const [path, setPath] = useState(location.pathname + location.search);
  useEffect(() => { const onPop = () => setPath(location.pathname + location.search); window.addEventListener('popstate', onPop); return () => window.removeEventListener('popstate', onPop); }, []);
  const navigate = (to: string) => { history.pushState({}, '', to); setPath(to); window.scrollTo(0, 0); };
  return { path, navigate };
}
type Navigate = (to: string) => void;
function Logo() { return <span className="wordmark"><svg width="30" height="31" viewBox="0 0 30 31" aria-hidden="true"><path d="M2 2h26v7H10v4h14v7H10v9H2V2Z" fill="currentColor"/><path d="M17 23h11v6H17z" fill="#c65a32"/></svg><span>STEELWORK<small>FABRICATION PORTAL</small></span></span>; }
function IconButton({ children, label, onClick, disabled = false }: { children: React.ReactNode; label: string; onClick: () => void; disabled?: boolean }) { return <button className="icon-button" type="button" aria-label={label} onClick={onClick} disabled={disabled}>{children}</button>; }
function Badge({ review, children }: { review?: boolean; children: React.ReactNode }) { return <span className={`badge ${review ? 'review' : ''}`}><span/>{children}</span>; }
function ErrorBox({ text }: { text: string }) { return text ? <div role="alert" className="error-box">{text}</div> : null; }
function Busy() { return <div className="loading"><LoaderCircle className="spin" size={22}/> Loading your workspace…</div>; }
function Status({ value }: { value: string }) { return <span className={`status status-${value.toLowerCase()}`}>{value.replaceAll('_', ' ')}</span>; }

function Sketch({ product, length = 6000, shape = 'straight', leg = 600, technical = false, zoom = 1 }: { product: Product; length?: number; shape?: string; leg?: number; technical?: boolean; zoom?: number }) {
  const id = useId().replaceAll(':', '');
  const mesh = product.family === 'mesh', accessory = product.family === 'accessories';
  return <svg className={`sketch ${technical ? 'technical' : ''}`} viewBox="0 0 640 390" role="img" aria-label={`${product.name}, ${mesh ? `${product.widthMm} by ${product.heightMm} millimetres` : `${length} millimetres`}. Schematic only.`}>
    <defs><pattern id={id} width="24" height="24" patternUnits="userSpaceOnUse"><circle cx="1" cy="1" r=".8" fill="#bdc5bd"/></pattern><linearGradient id={`${id}bar`} x1="0" y1="0" x2="0" y2="1"><stop stopColor="#8b938a"/><stop offset=".45" stopColor="#555f56"/><stop offset="1" stopColor="#2f3b32"/></linearGradient><marker id={`${id}arrow`} markerWidth="6" markerHeight="6" refX="3" refY="3" orient="auto-start-reverse"><path d="M6 0 0 3 6 6" fill="none" stroke="#7a8279"/></marker></defs>
    {technical && <rect width="640" height="390" fill={`url(#${id})`}/>}
    <g transform={`translate(320 195) scale(${zoom}) translate(-320 -195)`}>
    {mesh ? <g transform="translate(128 98) skewY(-12)"><rect width="380" height="190" rx="1" fill="#c1c9bc" fillOpacity=".15" stroke="#52624f" strokeWidth="3"/>{Array.from({ length: 16 }, (_, i) => <line key={`v${i}`} x1={i * 25} x2={i * 25} y1="0" y2="190" stroke="#61715e" strokeWidth="2.5"/>)}{Array.from({ length: 8 }, (_, i) => <line key={`h${i}`} x1="0" x2="380" y1={i * 27} y2={i * 27} stroke="#61715e" strokeWidth="2.5"/>)}</g> : accessory ? <g transform="translate(250 95)"><path d="m-15 185 40-150h55l45 150M0 135h105M25 35q25-35 55 0" fill="none" stroke="#3f5144" strokeWidth="14" strokeLinejoin="round"/><path d="M-40 185H5m96 0h45" stroke="#3f5144" strokeWidth="12" strokeLinecap="round"/></g> : shape === 'straight' ? <g transform="rotate(-14 320 190)"><rect x="100" y="172" width="440" height="26" rx="12" fill={`url(#${id}bar)`}/>{Array.from({ length: 31 }, (_, i) => <path key={i} d={`M${113 + i * 14} 174l-8 18m9-1 7 6`} stroke="#adb3a6" strokeWidth="2.5"/>)}<ellipse cx="100" cy="185" rx="5" ry="12" fill="#c4c8b9"/><path d="M115 179h400" stroke="#bbc3b1" opacity=".45"/></g> : <g><path d={shape === 'U' ? 'M195 110v155q0 20 20 20h210q20 0 20-20V110' : 'M190 105v155q0 23 23 23h270'} fill="none" stroke="#4e6052" strokeWidth="18" strokeLinecap="round"/>{Array.from({ length: 10 }, (_, i) => <path key={i} d={`M183 ${115 + i * 14}l14 6`} stroke="#a6b19d" strokeWidth="2"/>)}</g>}
    {technical && <g stroke="#7a8279" fill="none" strokeWidth="1"><path d="M105 275v48M535 185v138" strokeDasharray="3 4"/><path d="M110 312h420" markerStart={`url(#${id}arrow)`} markerEnd={`url(#${id}arrow)`}/><rect x="263" y="300" width="114" height="23" fill="#f3f4ed" stroke="none"/><text x="320" y="316" fill="#4b574c" stroke="none" textAnchor="middle" fontSize="13" fontFamily="monospace">{(mesh ? product.widthMm : length)?.toLocaleString()} mm</text>{shape !== 'straight' && <text x="140" y="190" fill="#4b574c" stroke="none" fontSize="13" transform="rotate(-90 140 190)">Leg B · {leg} mm</text>}</g>}
    </g>
    {technical && <><g transform="translate(35 337)" strokeWidth="1.5"><path d="M0 0v-29M0 0h30" stroke="#637363"/><text x="34" y="4" fontSize="10" fill="#637363">X</text><text x="-3" y="-36" fontSize="10" fill="#637363">Y</text></g><text x="604" y="365" textAnchor="end" fontFamily="monospace" fontSize="10" fill="#7a8279">SCHEMATIC · NOT TO SCALE</text></>}
  </svg>;
}

function App() {
  const { path, navigate } = useRoute();
  const [products, setProducts] = useState<Product[]>([]), [user, setUser] = useState<Identity | null>(null), [demo, setDemo] = useState(false);
  const [cart, setCart] = useState<Line[]>([]), [loading, setLoading] = useState(true), [error, setError] = useState(''), [help, setHelp] = useState(false), [toast, setToast] = useState('');
  async function loadCart() { const result = await api<{ lines: Line[] }>('/cart'); setCart(result.lines); }
  async function switchUser(userId: string) { try { setLoading(true); if (userId === 'visitor') { await api('/session', 'DELETE'); setUser(null); setCart([]); } else { await api('/session', 'POST', { userId }); const result = await api<{ user: Identity }>('/session'); setUser(result.user); await loadCart(); } setError(''); } catch (e) { setError(message(e)); } finally { setLoading(false); } }
  useEffect(() => { let live = true; async function start() { try { const [catalogue, session] = await Promise.all([api<{ products: Product[] }>('/products'), api<{ user: Identity | null; demoEnabled: boolean }>('/session')]); if (!live) return; setProducts(catalogue.products); setDemo(session.demoEnabled); setUser(session.user); if (session.user) await loadCart(); } catch (e) { if (live) setError(message(e)); } finally { if (live) setLoading(false); } } void start(); return () => { live = false; }; }, []);
  useEffect(() => { if (!toast) return; const timer = setTimeout(() => setToast(''), 4500); return () => clearTimeout(timer); }, [toast]);
  const pathname = path.split('?')[0], configActive = pathname.startsWith('/configure');
  async function addLine(config: Configuration) { if (!user) throw new Error('Choose a customer from the Demo workspace menu above to save items.'); const result = await api<{ lines: Line[] }>('/cart', 'POST', config); setCart(result.lines); setToast('Configuration added to your quote cart.'); }
  return <><div className="demo-strip"><span className="demo-tag">LOCAL DEMO</span><span>A working prototype. Synthetic rates, schematic drawings, no real orders.</span><span className="demo-region">AU / AUD</span></div>
    <header className="header"><button className="brand" onClick={() => navigate('/products')} aria-label="Steelwork home"><Logo/></button><nav aria-label="Main navigation"><button className={pathname==='/shop'?'active':''} onClick={()=>navigate('/shop')}>Shop products</button><button className={pathname==='/design'?'active':''} onClick={()=>navigate('/design')}>Design & configure</button><button className={pathname === '/products' || pathname === '/' ? 'active' : ''} onClick={() => navigate('/products')}>Products</button><button className={configActive ? 'active' : ''} onClick={() => navigate('/configure/bar')}>Configure <ChevronDown size={13}/></button><button className={pathname.startsWith('/quotes') ? 'active' : ''} onClick={() => navigate('/quotes')}>My quotes</button>{user?.role === 'estimator' && <button className={pathname === '/admin' ? 'active' : ''} onClick={() => navigate('/orders')}>Review queue</button>}</nav><div className="header-actions"><IconButton label="Help and demo information" onClick={() => setHelp(true)}><CircleHelp size={19}/></IconButton><button className={`cart-button ${pathname === '/cart' ? 'selected' : ''}`} onClick={() => navigate('/cart')}><ShoppingBag size={18}/><span>Quote cart</span><b>{cart.length}</b></button></div></header>
    <div className="workspace-bar"><span><span className="online-dot"/> Your fabrication workspace <span className="workspace-separator">/</span> <strong>{user?.organisationName ?? 'Explore as a visitor'}</strong></span>{demo && <label className="identity-select">Demo workspace <select aria-label="Demo workspace" value={user?.id ?? 'visitor'} onChange={e => void switchUser(e.target.value)}><option value="visitor">Visitor</option><option value="customer-river">Riverbank · Customer</option><option value="customer-coast">Coastal · Customer</option><option value="estimator">Steelwork · Estimator</option></select></label>}</div>
    <div className="account-links">{[['/parts','My Parts'],['/projects','My Projects'],['/quotes','My Quotes'],['/orders',user?.role==='estimator'?'Order validation':'My Orders']].map(([to,label])=><button key={to} className={pathname.startsWith(to)?'selected':''} onClick={()=>navigate(to)}>{label}</button>)}</div><main><ErrorBox text={error}/>{loading ? <Busy/> : products.length === 0 ? <div className="empty"><h1>Let’s set up the catalogue.</h1><p>Run the local database setup described in the README, then refresh.</p></div> : pathname === '/shop' ? <Shop key={user?.id} products={products} lines={cart} user={user} addLine={addLine} navigate={navigate} art={p=><Sketch product={p}/>}/> : pathname === '/design' ? <DesignLanding navigate={navigate}/> : pathname === '/parts' ? <MyParts key={`${path}-${user?.id}`} products={products} navigate={navigate} refreshCart={loadCart}/> : pathname === '/projects' ? <Projects key={user?.id} navigate={navigate}/> : pathname === '/checkout' ? <Checkout key={user?.id} lines={cart} user={user} navigate={navigate} onSubmitted={()=>setCart([])}/> : pathname === '/orders' ? <OrdersList key={`${path}-${user?.id}`} user={user} navigate={navigate}/> : /^\/orders\/[^/]+$/.test(pathname) ? <OrderDetail key={`${pathname}-${user?.id}`} id={pathname.split('/')[2]} user={user} products={products} navigate={navigate}/> : pathname === '/' || pathname === '/products' ? <Catalogue products={products} navigate={navigate}/> : configActive && (pathname === '/configure/bar' || pathname === '/configure/shapes') ? <BarConfigurator key={path} products={products} path={path} addLine={addLine} navigate={navigate} user={user}/> : configActive && pathname === '/configure/mesh' ? <MeshConfigurator key={path} products={products} path={path} addLine={addLine} navigate={navigate} user={user}/> : configActive ? <Configurator key={path} products={products} path={path} addLine={addLine} navigate={navigate} user={user}/> : pathname === '/cart' ? <Cart lines={cart} setLines={setCart} navigate={navigate} user={user}/> : /^\/quotes\/[^/]+$/.test(pathname) ? <QuoteDetail key={`${pathname}-${user?.id}`} id={pathname.split('/')[2]} user={user} navigate={navigate}/> : pathname === '/quotes' || pathname === '/admin' ? <QuoteList key={`${pathname}-${user?.id}`} user={user} navigate={navigate} admin={pathname === '/admin'}/> : <div className="empty"><h1>Page not found</h1><button className="primary" onClick={() => navigate('/products')}>Browse products <ArrowRight size={16}/></button></div>}</main>
    <footer className="footer"><span>STEELWORK <span className="muted">/ Original fabrication portal prototype</span></span><span>Australian metric · AUD · Brisbane time</span></footer>
    {toast && <div className="toast" role="status"><Check size={18}/>{toast}<button onClick={() => navigate('/cart')}>View cart <ArrowRight size={14}/></button></div>}
    {help && <div className="modal-backdrop" onClick={() => setHelp(false)}><section className="help-modal" role="dialog" aria-modal="true" aria-labelledby="help-title" onClick={e => e.stopPropagation()}><div className="modal-title"><h2 id="help-title">Built for a clearer quote.</h2><IconButton label="Close help" onClick={() => setHelp(false)}><X/></IconButton></div><p>Choose a local demo workspace to save a cart and submit a request. Switch to the Estimator workspace to review it and issue a demonstration quote revision.</p><p>All products, availability, rates and mass values are synthetic. Drawings are schematic; no engineering certification, fabrication schedule, payment or manufacturing order is produced.</p><p>Private drawing uploads and production authentication are planned for the next delivery. The local account selector is disabled outside localhost.</p><button className="primary" onClick={() => setHelp(false)}>Got it <Check size={16}/></button></section></div>}
  </>;
}

function Catalogue({ products, navigate }: { products: Product[]; navigate: Navigate }) {
  const [family, setFamily] = useState('all'), [search, setSearch] = useState(''), [mode, setMode] = useState('all');
  const filtered = products.filter(p => (family === 'all' || p.family === family) && `${p.name} ${p.sku}`.toLowerCase().includes(search.toLowerCase()) && (mode === 'all' || mode === 'priced' && p.quoteMode !== 'REVIEW_REQUIRED' || mode === 'review' && p.quoteMode === 'REVIEW_REQUIRED'));
  return <><section className="catalogue-hero"><div><div className="eyebrow"><span/> SPECIFY. CONFIGURE. GET QUOTED.</div><h1>Reinforcement,<br/><span>without the back-and-forth.</span></h1><p>Find your stock. Set your dimensions. Build a clear,<br className="desktop-break"/> traceable quote request — all in one place.</p><button className="primary" onClick={() => navigate('/configure/bar')}>Configure your reinforcement <ArrowRight size={17}/></button><div className="hero-foot"><ShieldCheck size={15}/>Transparent demo pricing <span>·</span> Metric by design</div></div><div className="hero-drawing"><Sketch product={products.find(p => p.family === 'mesh')!}/><div className="hero-drawing-label"><span>01 / REINFORCING MESH</span><span>PRECISION STARTS WITH A PLAN</span></div></div><span className="hero-corner">EST. IN YOUR WORKSPACE</span></section>
    <section className="catalogue-layout"><aside className="catalogue-sidebar"><div className="small-title">PRODUCT FAMILIES</div><button className={family === 'all' ? 'selected' : ''} onClick={() => setFamily('all')}><Grid2X2 size={17}/>All products <span>{products.length}</span></button>{Object.entries(familyName).map(([key, label]) => <button key={key} className={family === key ? 'selected' : ''} onClick={() => setFamily(key)}>{key === 'mesh' ? <Grid2X2 size={17}/> : key === 'accessories' ? <Package size={17}/> : key === 'fabrication' ? <Ruler size={17}/> : <Layers size={17}/>} {label}<span>{products.filter(p => p.family === key).length}</span></button>)}<div className="sidebar-note"><FileText size={23}/><h3>Something more complex?</h3><p>Capture your dimensions for a manual fabrication review.</p><button onClick={() => navigate('/configure/shapes')}>Configure a custom shape <ArrowUpRight size={16}/></button></div></aside>
    <div className="catalogue-results"><div className="section-heading"><div><div className="eyebrow">THE DEMO CATALOGUE</div><h2>{family === 'all' ? 'Start with the right material.' : familyName[family as keyof typeof familyName]}</h2></div><span className="result-count">{filtered.length} products</span></div><div className="catalogue-toolbar"><div className="filter-pills"><button className={mode === 'all' ? 'chosen' : ''} onClick={() => setMode('all')}>All products</button><button className={mode === 'priced' ? 'chosen' : ''} onClick={() => setMode('priced')}>Indicative pricing</button><button className={mode === 'review' ? 'chosen' : ''} onClick={() => setMode('review')}>Manual review</button></div><label className="search"><Search size={16}/><input aria-label="Search products" placeholder="Search name or SKU" value={search} onChange={e => setSearch(e.target.value)}/></label></div><div className="product-grid">{filtered.map(p => <button className="product-card" key={p.id} onClick={() => navigate(routeFor(p))}><div className="product-art"><span className="art-index">{p.sku}</span><Sketch product={p} shape={p.family === 'fabrication' ? 'L' : 'straight'}/><span className="card-open"><ArrowUpRight size={18}/></span></div><div className="product-info"><Badge review={p.quoteMode === 'REVIEW_REQUIRED'}>{p.quoteMode === 'REVIEW_REQUIRED' ? 'Manual review' : p.quoteMode === 'RULE_BASED' ? 'Made to length' : 'Stock format'}</Badge><h3>{p.name}</h3><p>{p.description}</p><div className="product-price"><span>{p.rateCents ? <>From <strong>{money(p.rateCents)}</strong><small> / {p.unit}</small></> : <strong>Request a quote</strong>}</span><span className="demo-price">DEMO · EX GST</span></div></div></button>)}</div>{filtered.length === 0 && <div className="empty"><Search/><h3>No matching products</h3><p>Try another name, family or pricing filter.</p></div>}<div className="catalogue-disclaimer"><ShieldCheck size={17}/><p>Built for an informed decision. All catalogue specifications and prices are demonstrative and require supplier verification before real use.</p></div></div></section></>;
}

function Configurator({ products, path, addLine, navigate, user }: { products: Product[]; path: string; addLine: (c: Configuration) => Promise<void>; navigate: Navigate; user: Identity | null }) {
  const family = path.includes('/mesh') ? 'mesh' : path.includes('/accessories') ? 'accessories' : path.includes('/shapes') ? 'fabrication' : 'bar';
  const available = products.filter(p => p.family === family), initialId = new URLSearchParams(path.split('?')[1]).get('product');
  const [productId, setProductId] = useState(available.find(p => p.id === initialId)?.id ?? available[0].id), [length, setLength] = useState(6000), [quantity, setQuantity] = useState(1), [shape, setShape] = useState<Configuration['shape']>(family === 'fabrication' ? 'L' : 'straight'), [leg, setLeg] = useState(600), [reference, setReference] = useState(''), [notes, setNotes] = useState('');
  const [price, setPrice] = useState<Price | null>(null), [pricing, setPricing] = useState(true), [error, setError] = useState(''), [saveError, setSaveError] = useState(''), [saving, setSaving] = useState(false), [added, setAdded] = useState(false), [zoom, setZoom] = useState(1);
  const product = products.find(p => p.id === productId)!;
  const configuration: Configuration = { productId, lengthMm: length, quantity, shape, legBMm: leg, reference, notes };
  useEffect(() => { const controller = new AbortController(); setPricing(true); setPrice(null); setError(''); setAdded(false); const timer = setTimeout(() => { fetch('/api/price', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ productId, lengthMm: length, quantity, shape, legBMm: leg, reference: '', notes: '' }), signal: controller.signal }).then(async r => { const data = await r.json() as { price: Price; error?: string }; if (!r.ok) throw new Error(data.error); return data; }).then(data => { setPrice(data.price); setPricing(false); }).catch(e => { if (!controller.signal.aborted) { setError(message(e)); setPricing(false); } }); }, 240); return () => { clearTimeout(timer); controller.abort(); }; }, [productId, length, quantity, shape, leg]);
  async function save() { setSaving(true); setSaveError(''); try { await addLine(configuration); setAdded(true); } catch (e) { setSaveError(message(e)); } finally { setSaving(false); } }
  return <section className="configure-page"><div className="breadcrumbs"><button onClick={() => navigate('/products')}>Products</button><ChevronRight size={13}/><span>{familyName[family]}</span><ChevronRight size={13}/><strong>Configure</strong></div><div className="config-heading"><div><div className="eyebrow">YOUR SPECIFICATION, MADE CLEAR</div><h1>Configure your reinforcement.</h1></div><span className="save-hint"><span className="online-dot"/> Local workspace</span></div><div className="config-tabs">{([['bar', 'Straight bar'], ['mesh', 'Stock mesh'], ['accessories', 'Accessories'], ['shapes', 'Bent shapes']] as const).map(([key, label]) => <button key={key} className={path.includes('/' + key) ? 'active' : ''} onClick={() => navigate('/configure/' + key)}>{label}{key === 'shapes' && <span>REVIEW</span>}</button>)}</div>
    <div className="config-workbench"><div className="configuration-panel"><div className="panel-title"><span className="step-number">01</span><h2>Specification</h2><SlidersHorizontal size={17}/></div><div className="form-body"><label className="field">Product<select value={productId} onChange={e => setProductId(e.target.value)}>{available.map(p => <option key={p.id} value={p.id}>{p.name}</option>)}</select></label><div className="spec-chips"><span>{product.diameterMm ? `Ø ${product.diameterMm} mm` : `Pack of ${product.rules.packSize}`}</span><span>Synthetic SKU</span></div>
    {family === 'fabrication' && <label className="field">Shape<select value={shape} onChange={e => setShape(e.target.value as Configuration['shape'])}><option value="L">L shape</option><option value="U">U shape</option></select></label>}
    {(family === 'bar' || family === 'fabrication') && <label className="field">{family === 'fabrication' ? 'Leg A' : 'Length'}<div className="input-unit">{product.quoteMode === 'STOCK_PRICE' ? <select aria-label="Length" value={length} onChange={e => setLength(Number(e.target.value))}>{product.rules.stockLengthsMm.map(v => <option key={v} value={v}>{v.toLocaleString()}</option>)}</select> : <input aria-label={family === 'fabrication' ? 'Leg A' : 'Length'} type="number" min={product.rules.minLengthMm} max={product.rules.maxLengthMm} step={product.rules.lengthStepMm} value={length} onChange={e => setLength(Number(e.target.value))}/>}<span>mm</span></div><small>{product.quoteMode === 'STOCK_PRICE' ? 'Available demonstration stock lengths' : `${product.rules.minLengthMm.toLocaleString()}–${product.rules.maxLengthMm.toLocaleString()} mm · ${product.rules.lengthStepMm} mm increments`}</small></label>}
    {family === 'fabrication' && <label className="field">Leg B<div className="input-unit"><input aria-label="Leg B" type="number" min="100" step="50" value={leg} onChange={e => setLeg(Number(e.target.value))}/><span>mm</span></div></label>}
    {family === 'mesh' && <div className="dimension-readout"><span>Stock sheet dimensions</span><strong>{product.widthMm?.toLocaleString()} × {product.heightMm?.toLocaleString()} <small>mm</small></strong><span>Spacing shown is schematic</span></div>}
    <label className="field">Quantity <span className="field-optional">{product.unit === 'pack' ? 'packs' : product.unit === 'sheet' ? 'sheets' : 'pieces'}</span><div className="quantity-control"><IconButton label="Decrease quantity" onClick={() => setQuantity(Math.max(1, quantity - 1))} disabled={quantity <= 1}><Minus size={15}/></IconButton><input aria-label="Quantity" type="number" min="1" max="999" value={quantity} onChange={e => setQuantity(Number(e.target.value))}/><IconButton label="Increase quantity" onClick={() => setQuantity(Math.min(999, quantity + 1))}><Plus size={15}/></IconButton></div></label><div className="form-divider"/><label className="field">Project reference <span className="field-optional">optional</span><input placeholder="e.g. Ground floor / Zone A" maxLength={120} value={reference} onChange={e => setReference(e.target.value)}/></label><label className="field">Notes <span className="field-optional">optional</span><textarea placeholder="Anything our estimator should know?" maxLength={2000} rows={3} value={notes} onChange={e => setNotes(e.target.value)}/></label></div></div>
    <div className="preview-panel"><div className="preview-top"><span><span className="online-dot"/> LIVE SCHEMATIC</span><span>2D / METRIC</span></div><div className="preview-canvas"><Sketch product={product} length={length} leg={leg} shape={shape} technical zoom={zoom}/></div><div className="preview-toolbar"><div><span className="view-label">2D view</span><span className="preview-units">mm</span></div><div><IconButton label="Zoom out" onClick={() => setZoom(Math.max(.7, zoom - .1))}><ZoomOut size={17}/></IconButton><button className="zoom-reset" onClick={() => setZoom(1)}>{Math.round(zoom * 100)}%</button><IconButton label="Zoom in" onClick={() => setZoom(Math.min(1.4, zoom + .1))}><ZoomIn size={17}/></IconButton></div></div><div className="drawing-caption"><Ruler size={16}/><p>Conceptual preview only. Not a certified fabrication drawing or approved engineering design.</p></div><div className="preview-specification"><div><span>PRODUCT REFERENCE</span><strong>{product.sku}</strong></div><div><span>FORMAT</span><strong>{familyName[family]}</strong></div><div><span>FINISH</span><strong>Demonstration stock</strong></div></div></div>
    <aside className="quote-panel"><div className="panel-title"><span className="step-number">02</span><h2>Your indicative quote</h2></div><div className="quote-panel-body"><div className="price-state"><span>DEMO RATE BOOK</span><Badge review={price?.requiresReview}>{price?.requiresReview ? 'Review required' : 'Indicative price'}</Badge></div><h3>{product.name}</h3><p className="quote-description">{quantity} {product.unit === 'pack' ? `pack${quantity === 1 ? '' : 's'}` : product.unit === 'sheet' ? `sheet${quantity === 1 ? '' : 's'}` : `piece${quantity === 1 ? '' : 's'}${shape === 'straight' ? ` · ${(length / 1000).toFixed(2)} m each` : ' · custom shape'}`}</p><ErrorBox text={error}/>{pricing ? <div className="pricing-wait"><LoaderCircle size={19} className="spin"/> Calculating on server…</div> : price?.requiresReview ? <div className="review-price"><FileText size={26}/><strong>Let’s review the details.</strong><p>This shape needs a fabrication review. No instant price or developed length is calculated.</p></div> : price && <><dl className="price-breakdown"><div><dt>Material & configuration</dt><dd>{money(price.subtotalCents)}</dd></div><div><dt>GST ({product.rules.taxBps / 100}%)</dt><dd>{money(price.gstCents)}</dd></div><div><dt>Delivery</dt><dd className="muted">To be quoted</dd></div></dl><div className="quote-total"><span>Goods total <small>incl. GST</small></span><strong>{money(price.totalCents)}</strong></div><div className="weight-row"><span>Indicative mass</span><span>{price.massKg?.toFixed(2)} kg</span></div></>}
    <ErrorBox text={saveError}/><button className={`primary add-button ${added ? 'added' : ''}`} disabled={saving || pricing || !!error || !price} onClick={() => void save()}>{saving ? <LoaderCircle size={17} className="spin"/> : added ? <Check size={17}/> : <Plus size={17}/>} {saving ? 'Saving…' : added ? 'Added to quote cart' : 'Add to quote cart'}</button>{added && <button className="secondary full" onClick={() => navigate('/cart')}>Review cart <ArrowRight size={16}/></button>}{!user && <p className="visitor-hint">To save, select a customer in the Demo workspace menu.</p>}<div className="quote-fineprint"><ShieldCheck size={16}/><p>Transparent assumptions.<br/>No payment or order is placed.</p></div></div><div className="assumptions"><h4>Good to know</h4><ul><li>Synthetic rates · DEMO-2026.1</li><li>Delivery and lead times require confirmation</li><li>All specifications require verification</li></ul></div></aside></div>
  </section>;
}

function LineCards({ lines, remove }: { lines: Line[]; remove?: (id: string) => void }) { return <div className="line-list">{lines.map(line => <article className="line-card" key={line.id}><div className="line-art">{line.configuration.mesh ? <MeshThumbnail configuration={line.configuration.mesh} product={line.product}/> : line.configuration.editor ? <BarThumbnail configuration={line.configuration.editor}/> : <Sketch product={line.product} shape={line.configuration.shape}/>}</div><div className="line-info"><span className="small-title">{line.product.sku}</span><h3>{line.product.name}</h3><p>{line.configuration.quantity} {line.product.unit === 'sheet' ? 'sheet(s)' : line.product.unit === 'pack' ? 'pack(s)' : `piece(s) · ${line.configuration.lengthMm.toLocaleString()} mm`}{line.configuration.shape !== 'straight' ? ` · ${line.configuration.shape} shape` : ''}</p>{line.configuration.mesh && <p className="line-notes">{line.configuration.mesh.lengthMm} × {line.configuration.mesh.widthMm} mm · Ø{line.configuration.mesh.diameterMm} · {line.configuration.mesh.longitudinalSpacingMm}/{line.configuration.mesh.transverseSpacingMm} mm grid · {line.configuration.mesh.grade} · {line.configuration.mesh.finish} · {line.configuration.mesh.rulesVersion}</p>}{line.configuration.editor && <p className="line-notes">Ø{line.configuration.editor.diameterMm} · {line.configuration.editor.grade} · {line.configuration.editor.finish} · A {line.configuration.editor.aMm} / B {line.configuration.editor.bMm} / C {line.configuration.editor.cMm} mm · {line.configuration.editor.rulesVersion}</p>}{line.configuration.reference && <span className="reference-tag">{line.configuration.reference}</span>}{line.configuration.notes && <p className="line-notes">{line.configuration.notes}</p>}</div><div className="line-price"><strong>{money(line.price.totalCents)}</strong><small>{line.price.requiresReview ? 'MANUAL REVIEW' : 'DEMO · INCL. GST'}</small>{remove && <IconButton label={`Remove ${line.product.name}`} onClick={() => remove(line.id)}><Trash2 size={16}/></IconButton>}</div></article>)}</div>; }

function Cart({ lines, setLines, navigate, user }: { lines: Line[]; setLines: (l: Line[]) => void; navigate: Navigate; user: Identity | null }) {
  const [notes, setNotes] = useState(''), [error, setError] = useState(''), [saving, setSaving] = useState(false);
  const totals = sumLines(lines);
  async function remove(id: string) { try { setError(''); const result = await api<{ lines: Line[] }>('/cart/' + id, 'DELETE'); setLines(result.lines); } catch (e) { setError(message(e)); } }
  async function submit() { setSaving(true); setError(''); try { const result = await api<{ id: string }>('/quotes', 'POST', { notes }); setLines([]); navigate('/quotes/' + result.id); } catch (e) { setError(message(e)); } finally { setSaving(false); } }
  return <section className="document-page"><div className="breadcrumbs"><button onClick={() => navigate('/products')}>Workspace</button><ChevronRight size={13}/><span>Quote cart</span></div><div className="page-heading"><div><div className="eyebrow">ONE CLEAR REQUEST</div><h1>Your quote cart<span className="heading-count">{lines.length}</span></h1><p>Review your configurations before sending them to the demo estimating queue.</p></div><button className="secondary" onClick={() => navigate('/products')}><Plus size={16}/> Add more products</button></div><ErrorBox text={error}/>{!lines.length ? <Empty title={user ? 'Your next project starts here.' : 'Save your first configuration.'} text={user ? 'Configure a product and add it to your cart. Your work is saved to this organisation.' : 'Choose a customer from the Demo workspace menu, then configure a product.'} icon={<ShoppingBag size={32}/>} action="Explore products" onClick={() => navigate('/products')}/> : <div className="document-columns"><div><div className="enterprise-panel"><h3>Continue with complete customer & job details</h3><p>Create a stock/configured order request for validation, exact quote acceptance and local release.</p><button className="primary" onClick={()=>navigate('/checkout')}>Continue to order intake<ArrowRight size={15}/></button></div><LineCards lines={lines} remove={id => void remove(id)}/><section className="notes-card"><h3>Project notes</h3><label className="field">Context for the estimator<textarea rows={4} value={notes} maxLength={2000} onChange={e => setNotes(e.target.value)} placeholder="Project, delivery location, timing or fabrication requirements…"/></label></section></div><aside className="summary-card"><div className="small-title">REQUEST SUMMARY</div><h2>{lines.length} configuration{lines.length === 1 ? '' : 's'}</h2><dl className="price-breakdown"><div><dt>Priced goods ex. GST</dt><dd>{money(totals.subtotalCents)}</dd></div><div><dt>GST on priced goods</dt><dd>{money(totals.gstCents)}</dd></div><div><dt>Delivery</dt><dd>To be quoted</dd></div>{totals.reviewCount > 0 && <div><dt>Manual-review lines</dt><dd>{totals.reviewCount}</dd></div>}</dl><div className="quote-total"><span>{totals.reviewCount ? 'Priced portion' : 'Goods total'}<small>incl. GST</small></span><strong>{money(totals.totalCents)}</strong></div>{totals.reviewCount > 0 && <p className="notice">The full request total will be quoted after manual review.</p>}<button className="primary full" onClick={() => void submit()} disabled={saving}>{saving ? <LoaderCircle className="spin" size={16}/> : <ArrowUpRight size={17}/>}Submit quote request</button><p className="muted fine-text">Creates a tracked demo request. It does not place an order or reserve stock.</p></aside></div>}</section>;
}
function Empty({ title, text, icon, action, onClick }: { title: string; text: string; icon: React.ReactNode; action: string; onClick: () => void }) { return <div className="empty empty-card"><div className="empty-icon">{icon}</div><h2>{title}</h2><p>{text}</p><button className="primary" onClick={onClick}>{action}<ArrowRight size={16}/></button></div>; }
function QuoteList({ user, navigate, admin }: { user: Identity | null; navigate: Navigate; admin: boolean }) {
  const [quotes, setQuotes] = useState<Quote[]>([]), [loading, setLoading] = useState(true), [error, setError] = useState(''), [filter, setFilter] = useState('ALL');
  useEffect(() => { if (!user) { setLoading(false); return; } let live = true; api<{ quotes: Quote[] }>('/quotes').then(r => { if (live) setQuotes(r.quotes); }).catch(e => { if (live) setError(message(e)); }).finally(() => { if (live) setLoading(false); }); return () => { live = false; }; }, [user]);
  if (admin && user?.role !== 'estimator') return <Empty title="Estimator workspace" text="Choose Steelwork · Estimator in the Demo workspace menu to access the review queue." icon={<ShieldCheck/>} action="My quotes" onClick={() => navigate('/quotes')}/>;
  return <section className="document-page"><div className="page-heading"><div><div className="eyebrow">{admin ? 'ESTIMATOR WORKSPACE' : 'YOUR PROJECTS, IN ONE PLACE'}</div><h1>{admin ? 'Review queue.' : 'My quotes.'}</h1><p>{admin ? 'Review specifications and issue versioned demonstration quotes.' : 'Follow a request from specification to estimator review.'}</p></div><button className="primary" onClick={() => navigate('/products')}><Plus size={16}/> New quote request</button></div><div className="quote-stats"><div><span>Total requests</span><strong>{quotes.length.toString().padStart(2, '0')}</strong></div><div><span>Awaiting review</span><strong>{quotes.filter(q => q.status === 'SUBMITTED').length.toString().padStart(2, '0')}</strong></div><div><span>In review</span><strong>{quotes.filter(q => q.status === 'UNDER_REVIEW').length.toString().padStart(2, '0')}</strong></div><div><span>Quoted</span><strong>{quotes.filter(q => q.status === 'QUOTED').length.toString().padStart(2, '0')}</strong></div></div><ErrorBox text={error}/><div className="filter-pills list-filters">{['ALL', 'SUBMITTED', 'UNDER_REVIEW', 'QUOTED'].map(s => <button key={s} className={filter === s ? 'chosen' : ''} onClick={() => setFilter(s)}>{s === 'ALL' ? 'All requests' : s.replaceAll('_', ' ').toLowerCase()}</button>)}</div>{loading ? <Busy/> : !user || !quotes.length ? <Empty title={user ? 'A clear record of what comes next.' : 'Your workspace is waiting.'} text={user ? 'Your submitted quote requests will appear here, with version history and review status.' : 'Choose a local demo customer above to view saved requests.'} icon={<ClipboardList size={30}/>} action="Build a quote" onClick={() => navigate('/products')}/> : <div className="quotes-table"><div className="quotes-table-head"><span>REQUEST / PROJECT</span><span>CREATED</span><span>STATUS</span><span>GOODS TOTAL</span></div>{quotes.filter(q => filter === 'ALL' || q.status === filter).map(q => <button className="quote-row" key={q.id} onClick={() => navigate('/quotes/' + q.id)}><span><strong>{q.reference}</strong><small>{q.organisation_name} · {q.lines.length} configuration(s)</small></span><span>{date(q.created_at, false)}</span><span><Status value={q.status}/></span><span><strong>{money(q.total_cents)}</strong><ChevronRight size={17}/></span></button>)}</div>}</section>;
}
const date = (value: string, time = true) => new Intl.DateTimeFormat('en-AU', { timeZone: 'Australia/Brisbane', day: 'numeric', month: 'short', year: 'numeric', ...(time ? { hour: 'numeric', minute: '2-digit' } : {}) }).format(new Date(value));
function QuoteDetail({ id, user, navigate }: { id: string; user: Identity | null; navigate: Navigate }) {
  const [quote, setQuote] = useState<Quote | null>(null), [error, setError] = useState(''), [loading, setLoading] = useState(true), [note, setNote] = useState(''), [subtotal, setSubtotal] = useState(''), [saving, setSaving] = useState(false);
  async function refresh() { const result = await api<{ quote: Quote }>('/quotes/' + id); setQuote(result.quote); setSubtotal(result.quote.subtotal_cents === null ? '' : (result.quote.subtotal_cents / 100).toFixed(2)); }
  useEffect(() => { let live = true; api<{ quote: Quote }>('/quotes/' + id).then(r => { if (live) { setQuote(r.quote); setSubtotal(r.quote.subtotal_cents === null ? '' : (r.quote.subtotal_cents / 100).toFixed(2)); } }).catch(e => { if (live) setError(message(e)); }).finally(() => { if (live) setLoading(false); }); return () => { live = false; }; }, [id]);
  async function revise(status: string) { if (!quote) return; if (note.trim().length < 3) { setError('Add an estimator note (at least 3 characters).'); return; } if (status === 'QUOTED' && !/^\d+(\.\d{1,2})?$/.test(subtotal)) { setError('Enter an amount with up to two decimal places.'); return; } const [whole, fraction = ''] = subtotal.split('.'); const cents = Number(whole) * 100 + Number(fraction.padEnd(2, '0')); setSaving(true); setError(''); try { await api('/quotes/' + id, 'PATCH', { version: quote.version, status, note, ...(status === 'QUOTED' ? { subtotalCents: cents } : {}) }); await refresh(); setNote(''); } catch (e) { setError(message(e)); } finally { setSaving(false); } }
  if (loading) return <Busy/>;
  if (!quote) return <section className="document-page"><ErrorBox text={error}/><button className="secondary" onClick={() => navigate('/quotes')}><ChevronLeft size={16}/> Back to quotes</button></section>;
  return <section className="document-page"><div className="breadcrumbs"><button onClick={() => navigate('/quotes')}>My quotes</button><ChevronRight size={13}/><span>{quote.reference}</span></div><div className="page-heading"><div><div className="eyebrow">TRACKED DEMO REQUEST</div><h1>{quote.reference}<Status value={quote.status}/></h1><p>{quote.organisation_name} · Created {date(quote.created_at)} AEST · Version {quote.version}</p></div><button className="secondary" onClick={() => navigate('/quotes')}><ChevronLeft size={15}/> All quotes</button></div><ErrorBox text={error}/><div className="document-columns"><div><div className="submitted-banner"><Check size={20}/><div><strong>{quote.status === 'SUBMITTED' ? 'Your request is in the queue.' : quote.status === 'QUOTED' ? 'A demonstration quote revision is ready.' : 'An estimator is reviewing your request.'}</strong><p>Your submitted configuration and pricing assumptions are preserved as a snapshot.</p></div></div><OrderWorkspaceLink quoteId={quote.id} user={user} navigate={navigate}/><LineCards lines={quote.lines}/>{quote.notes && <section className="notes-card"><h3>Project notes</h3><p>{quote.notes}</p></section>}<section className="notes-card"><h3>Activity & revision history</h3><div className="timeline">{quote.events?.map(e => <div key={e.id}><span className="timeline-dot"/><strong>{e.status.replaceAll('_', ' ')}</strong><p>{e.note}</p><small>{e.actor_name} · {date(e.created_at)} AEST</small></div>)}</div>{quote.revisions?.map(r => <div className="revision" key={r.id}><FileText size={17}/><span>Issued at version {r.revision}<small>{r.note}</small></span><strong>{money(r.total_cents)}</strong></div>)}</section></div><aside><section className="summary-card"><div className="small-title">{quote.status === 'QUOTED' ? 'LATEST DEMO REVISION' : 'REQUEST SUMMARY'}</div><dl className="price-breakdown"><div><dt>Subtotal ex. GST</dt><dd>{money(quote.subtotal_cents)}</dd></div><div><dt>GST</dt><dd>{money(quote.gst_cents)}</dd></div><div><dt>Delivery</dt><dd>To be quoted</dd></div></dl><div className="quote-total"><span>Goods total<small>incl. GST</small></span><strong>{money(quote.total_cents)}</strong></div><p className="fine-text muted">Demonstration only. No production order, stock reservation or engineering approval.</p></section>{user?.role === 'estimator' && <section className="summary-card estimator-card"><div className="small-title">ESTIMATOR ACTIONS</div><h3>{quote.status === 'QUOTED' ? 'Create another revision' : 'Review this request'}</h3><label className="field">Review note<textarea aria-label="Review note" rows={3} maxLength={2000} value={note} onChange={e => setNote(e.target.value)}/></label>{quote.status === 'UNDER_REVIEW' && <label className="field">DEMO subtotal ex. GST (AUD)<input aria-label="DEMO subtotal ex. GST" inputMode="decimal" value={subtotal} onChange={e => setSubtotal(e.target.value)}/><small>Demo revision uses 10% GST on all goods.</small></label>}<button disabled={saving} className="primary full" onClick={() => void revise(quote.status === 'UNDER_REVIEW' ? 'QUOTED' : 'UNDER_REVIEW')}>{saving ? <LoaderCircle size={16} className="spin"/> : <ArrowRight size={16}/>} {quote.status === 'UNDER_REVIEW' ? 'Issue demo quote' : quote.status === 'QUOTED' ? 'Reopen for review' : 'Start review'}</button></section>}</aside></div></section>;
}

createRoot(document.getElementById('root')!).render(<React.StrictMode><App/></React.StrictMode>);
