import { useMemo, useState } from '@wordpress/element';
import { __, _n, sprintf } from '@wordpress/i18n';
import { useAnalyticsSettings } from '../SettingsStore';
import { Icon } from '../icons';
import { FS_TABS, MiniBars, MiniGrid, PreviewFrame, SheetWindow, SidePanel, StatusChip, WpMini } from './parts';
import { dayLabel, money, useSample } from './sample';
import { forecastStyleName } from '../../format';

const TEXT_DOMAIN = 'stock-sync-with-google-sheet-for-woocommerce';

const STATUS_NAMES = {
	out_of_stock: __( 'Out of stock', TEXT_DOMAIN ),
	low_stock: __( 'Low stock', TEXT_DOMAIN ),
	at_risk: __( 'Will run out soon', TEXT_DOMAIN ),
	overstock: __( 'Too much stock', TEXT_DOMAIN ),
	dead_stock: __( 'Not selling', TEXT_DOMAIN ),
	healthy: __( 'Healthy', TEXT_DOMAIN ),
};

const hh = ( h ) => `${ String( h ).padStart( 2, '0' ) }:00`;

/** Mini KPI strip used in the sidebar panel. */
const Kpis = ( { sample } ) => {
	const total = sample.revenue.slice( -28 ).reduce( ( a, b ) => a + b, 0 );
	return (
		<>
			<div className="ssgsw-side__kpis">
				<div><small>{ __( 'Revenue', TEXT_DOMAIN ) }</small><strong>{ money( sample.symbol, total ) }</strong></div>
				<div><small>{ __( 'Orders', TEXT_DOMAIN ) }</small><strong>{ Math.round( total / 40 ) }</strong></div>
			</div>
			<MiniBars values={ sample.revenue.slice( -28 ) } />
		</>
	);
};

const salesRows = ( sample, count, offsetStart = 1 ) => {
	const rows = [];
	for ( let d = 0; d < count; d++ ) {
		const p = sample.products[ d % sample.products.length ];
		rows.push( [ dayLabel( -( d + offsetStart ) ), p.sku, p.name, String( Math.max( 1, Math.round( p.units / ( 3 + ( d % 4 ) ) ) ) ), money( sample.symbol, p.revenue / ( 3 + ( d % 4 ) ) ) ] );
	}
	return rows;
};
const SALES_HEAD = [ __( 'Date', TEXT_DOMAIN ), 'SKU', __( 'Product', TEXT_DOMAIN ), __( 'Units', TEXT_DOMAIN ), __( 'Revenue', TEXT_DOMAIN ) ];

// ---- General ---------------------------------------------------------------------------------
const GeneralPreview = ( { sample } ) => {
	const { v } = useAnalyticsSettings();
	const on = !! v( 'enabled' );
	const wp = on && !! v( 'show_in_wp' );
	return (
		<>
			<SheetWindow
				menuOpen={ on }
				analyticsMenu={ on }
				tabs={ on ? FS_TABS.slice( 0, 4 ) : [] }
				activeTab={ on ? 'daily' : '' }
				sidebar={ <SidePanel><Kpis sample={ sample } /></SidePanel> }
				sidebarOpen={ on }
				off={ ! on }
			>
				{ on ? (
					<MiniGrid headers={ [ SALES_HEAD[ 0 ], 'SKU', SALES_HEAD[ 3 ], SALES_HEAD[ 4 ] ] } rows={ salesRows( sample, 6 ).map( ( r ) => [ r[ 0 ], r[ 1 ], r[ 3 ], r[ 4 ] ] ) } num={ [ 2, 3 ] } animateKey="on" />
				) : (
					<MiniGrid headers={ [ 'ID', __( 'Name', TEXT_DOMAIN ), __( 'Stock', TEXT_DOMAIN ), 'SKU' ] } rows={ sample.products.slice( 0, 6 ).map( ( p, i ) => [ String( 100 + i ), p.name, String( p.stock ), p.sku ] ) } num={ [ 2 ] } animateKey="off" />
				) }
			</SheetWindow>
			<WpMini analyticsTab={ wp } />
		</>
	);
};

// ---- Sheet sync ------------------------------------------------------------------------------
const nextRuns = ( freq, hour ) => {
	if ( freq === 'hourly' ) {
		return [ 1, 2, 3, 4 ].map( ( n ) => `${ __( 'Today', TEXT_DOMAIN ) } ${ hh( ( new Date().getHours() + n ) % 24 ) }` );
	}
	if ( freq === '6h' ) {
		return [ '00:00', '06:00', '12:00', '18:00' ].map( ( t ) => `${ __( 'Every day', TEXT_DOMAIN ) } ${ t }` ).slice( 0, 4 );
	}
	return [ 1, 2, 3 ].map( ( n ) => `${ dayLabel( n ) } ${ hh( hour ) }` );
};

const SyncPreview = ( { sample } ) => {
	const { v } = useAnalyticsSettings();
	const [ replay, setReplay ] = useState( 0 );
	const on = !! v( 'sync.enabled' );
	const method = v( 'sync.method' );
	const wordpress = method === 'cron';
	const rerecord = !! v( 'sync.rerecord_recent' );
	const orders = wordpress && !! v( 'sync.on_order_change' );
	const runs = nextRuns( v( 'sync.frequency' ), Number( v( 'sync.hour' ) ) || 0 );
	const rows = salesRows( sample, 8 );
	return (
		<>
			<SheetWindow menuOpen={ false } tabs={ FS_TABS.slice( 0, 3 ) } activeTab="daily" off={ false }>
				<MiniGrid
					headers={ SALES_HEAD }
					rows={ rows }
					num={ [ 3, 4 ] }
					highlight={ ( r ) => on && rerecord && r < 6 }
					animateKey={ `sync-${ replay }-${ on }-${ rerecord }` }
				/>
			</SheetWindow>
			<div className="ssgsw-flow">
				<div className={ `ssgsw-flow__who${ on ? '' : ' is-muted' }` }>
					<span className="ssgsw-flow__node">{ wordpress ? __( 'Your website', TEXT_DOMAIN ) : __( 'Google Sheets timer', TEXT_DOMAIN ) }</span>
					<span className="ssgsw-flow__arrow" aria-hidden="true"><Icon name="chevron" size={ 16 } /></span>
					<span className="ssgsw-flow__node is-sheet">{ __( 'Your Google Sheet', TEXT_DOMAIN ) }</span>
				</div>
				<ul className="ssgsw-timeline" aria-label={ __( 'Next updates', TEXT_DOMAIN ) }>
					{ on ? runs.map( ( r ) => <li key={ r }><span className="ssgsw-timeline__dot"></span>{ r }</li> ) : <li className="is-muted">{ __( 'No automatic updates', TEXT_DOMAIN ) }</li> }
					{ on && orders && <li className="is-order"><span className="ssgsw-timeline__dot"></span>{ __( '1 minute after each order', TEXT_DOMAIN ) }</li> }
					{ on && rerecord && <li className="is-fix"><span className="ssgsw-timeline__dot"></span>{ __( 'Every night: the last 7 days are re-checked', TEXT_DOMAIN ) }</li> }
				</ul>
				<button type="button" className="ssgsw-sp__replay" onClick={ () => setReplay( ( n ) => n + 1 ) }>
					<Icon name="sync" size={ 13 } /> { __( 'Replay: add past sales', TEXT_DOMAIN ) }
				</button>
			</div>
		</>
	);
};

// ---- Sheet report tabs -----------------------------------------------------------------------
const TabsPreview = ( { sample } ) => {
	const { v, meta, focusTab, setFocusTab } = useAnalyticsSettings();
	const catNames = useMemo( () => {
		const byId = {};
		( meta.product_categories || [] ).forEach( ( c ) => {
			byId[ c.id ] = c.name;
		} );
		return byId;
	}, [ meta ] );
	const tab = focusTab || 'daily';
	const goTab = ( id ) => {
		setFocusTab( id );
		const el = document.getElementById( `ssgsw-tabcard-${ id }` );
		if ( el ) {
			el.scrollIntoView( { behavior: 'smooth', block: 'center' } );
		}
	};
	const catsOf = ( key ) => ( v( `reports.${ key }.categories` ) || [] ).map( ( id ) => catNames[ id ] || `#${ id }` );
	const skusOf = ( key ) => v( `reports.${ key }.skus` ) || [];

	// Sample products filtered like the tab would be.
	const filtered = ( key ) => {
		const cats = catsOf( key );
		const skus = skusOf( key );
		let list = sample.products;
		if ( skus.length ) {
			list = skus.slice( 0, 8 ).map( ( sku, i ) => ( { ...( sample.products[ i % sample.products.length ] ), sku, name: sku } ) );
		} else if ( cats.length ) {
			list = sample.products.slice( 0, Math.min( 8, 2 + cats.length * 2 ) ).map( ( p, i ) => ( { ...p, cat: cats[ i % cats.length ] } ) );
		}
		return list;
	};

	let grid = null;
	let caption = '';
	if ( tab === 'daily' ) {
		const list = filtered( 'daily' );
		const since = v( 'reports.daily.mode' ) === 'since';
		const days = Number( v( 'reports.daily.days' ) ) || 30;
		const sinceDate = v( 'reports.daily.since' );
		grid = (
			<MiniGrid
				headers={ [ ...SALES_HEAD.slice( 0, 3 ), __( 'Units', TEXT_DOMAIN ), __( 'Revenue', TEXT_DOMAIN ) ] }
				rows={ list.slice( 0, 7 ).map( ( p, i ) => [ dayLabel( -( i + 1 ) ), p.sku, p.name, String( Math.max( 1, Math.round( p.units / 5 ) ) ), money( sample.symbol, p.revenue / 5 ) ] ) }
				num={ [ 3, 4 ] }
				animateKey={ `d-${ list.length }-${ list[ 0 ] && list[ 0 ].sku }` }
			/>
		);
		caption = since
			? sprintf( /* translators: %s: start date or "the first order" */ __( 'Everything since %s', TEXT_DOMAIN ), sinceDate || __( 'the first order', TEXT_DOMAIN ) )
			: sprintf( __( 'The last %d days, ending yesterday', TEXT_DOMAIN ), days );
	} else if ( tab === 'compare' ) {
		const list = filtered( 'compare' );
		const n = Number( v( 'reports.compare.days' ) ) || 7;
		const cols = Math.min( n, 5 );
		const heads = [ 'SKU', ...Array.from( { length: cols }, ( _, i ) => dayLabel( -( cols - i ) ) ), n > cols ? sprintf( '+%d', n - cols ) : __( 'vs before', TEXT_DOMAIN ) ].slice( 0, 7 );
		grid = (
			<MiniGrid
				headers={ heads }
				rows={ list.slice( 0, 6 ).map( ( p, i ) => [ p.sku, ...Array.from( { length: cols }, ( _, c ) => String( ( ( i * 3 + c * 5 ) % 9 ) + 1 ) ), { t: i % 2 ? '▼ 8%' : '▲ 12%', cls: i % 2 ? 'is-down' : 'is-up' } ] ) }
				num={ [ 1, 2, 3, 4, 5, 6 ] }
				animateKey={ `c-${ n }-${ list.length }-${ list[ 0 ] && list[ 0 ].sku }` }
			/>
		);
		caption = sprintf( __( 'One column per day for %d days, compared with the %d days before', TEXT_DOMAIN ), n, n );
	} else if ( tab === 'dashboard' ) {
		const days = Math.max( 7, Math.min( 90, Number( v( 'reports.dashboard.days' ) ) || 30 ) );
		const series = Array.from( { length: days }, ( _, i ) => sample.revenue[ i % sample.revenue.length ] );
		const total = series.reduce( ( a, b ) => a + b, 0 );
		grid = (
			<div className="ssgsw-dashmini">
				<div className="ssgsw-side__kpis"><div><small>{ __( 'Revenue', TEXT_DOMAIN ) }</small><strong>{ money( sample.symbol, total ) }</strong></div><div><small>{ __( 'Orders', TEXT_DOMAIN ) }</small><strong>{ Math.round( total / 40 ) }</strong></div></div>
				<MiniBars values={ series } height={ 70 } />
			</div>
		);
		caption = sprintf( __( 'Sales for the last %d days', TEXT_DOMAIN ), days );
	} else if ( tab === 'stock' ) {
		const chosen = v( 'reports.stock_health.statuses' ) || [];
		const shown = chosen.length ? chosen : [ 'out_of_stock', 'low_stock', 'at_risk', 'overstock', 'dead_stock' ];
		const list = filtered( 'stock_health' );
		grid = (
			<MiniGrid
				headers={ [ 'SKU', __( 'Stock', TEXT_DOMAIN ), __( 'List', TEXT_DOMAIN ) ] }
				rows={ shown.flatMap( ( s, si ) => list.slice( si, si + 2 ).map( ( p ) => [ p.sku, String( p.stock ), { t: STATUS_NAMES[ s ] || s, cls: `st-${ s }` } ] ) ).slice( 0, 8 ) }
				num={ [ 1 ] }
				animateKey={ shown.join( '-' ) + list.length }
			/>
		);
		caption = sprintf( __( 'Showing: %s', TEXT_DOMAIN ), shown.map( ( s ) => STATUS_NAMES[ s ] || s ).join( ', ' ) );
	} else {
		const days = Number( v( 'reports.insights.days' ) ) || 28;
		grid = (
			<div className="ssgsw-insmini">
				<p><b className="is-crit">{ __( 'Critical', TEXT_DOMAIN ) }</b> { sprintf( __( '%s runs out in 3 days', TEXT_DOMAIN ), sample.products[ 2 ].sku ) }</p>
				<p><b className="is-warn">{ __( 'Warning', TEXT_DOMAIN ) }</b> { __( 'Refunds are up this week', TEXT_DOMAIN ) }</p>
				<p><b className="is-info">{ __( 'Tip', TEXT_DOMAIN ) }</b> { __( 'Saturday is your best day', TEXT_DOMAIN ) }</p>
			</div>
		);
		caption = sprintf( __( 'Looking at the last %d days', TEXT_DOMAIN ), days );
	}

	return (
		<SheetWindow tabs={ FS_TABS } activeTab={ tab } onTab={ goTab }>
			{ grid }
			<p className="ssgsw-sw__caption">{ caption }</p>
		</SheetWindow>
	);
};

// ---- Which orders count ----------------------------------------------------------------------
const OrdersPreview = ( { sample } ) => {
	const { v, meta } = useAnalyticsSettings();
	const counted = v( 'data.statuses' ) || [];
	const statuses = ( meta.statuses || [] ).slice( 0, 8 );
	const orders = Array.from( { length: Math.max( 8, statuses.length ) }, ( _, i ) => {
		const p = sample.products[ i % sample.products.length ];
		const st = statuses[ i % Math.max( 1, statuses.length ) ] || { value: 'wc-completed', label: 'Completed' };
		const total = Math.round( p.revenue / Math.max( 1, p.units ) ) * ( 1 + ( i % 3 ) );
		return { id: 1042 + i, st, units: 1 + ( i % 3 ), total, on: counted.includes( st.value ) };
	} );
	const sum = orders.filter( ( o ) => o.on ).reduce( ( a, o ) => ( { u: a.u + o.units, r: a.r + o.total } ), { u: 0, r: 0 } );
	return (
		<SheetWindow tabs={ FS_TABS.slice( 0, 3 ) } activeTab="daily">
			<MiniGrid
				headers={ [ __( 'Order', TEXT_DOMAIN ), __( 'Status', TEXT_DOMAIN ), __( 'Units', TEXT_DOMAIN ), __( 'Total', TEXT_DOMAIN ), __( 'Counted', TEXT_DOMAIN ) ] }
				rows={ orders.map( ( o ) => [ `#${ o.id }`, o.st.label, String( o.units ), money( sample.symbol, o.total ), { t: o.on ? '✓' : '–', cls: o.on ? 'is-up' : 'is-muted' } ] ) }
				num={ [ 2, 3 ] }
				highlight={ ( r ) => orders[ r ] && orders[ r ].on }
				animateKey={ counted.join( ',' ) }
				min={ 8 }
			/>
			<div className="ssgsw-sw__totals">
				<span>{ __( 'Total counted', TEXT_DOMAIN ) }</span>
				<strong>{ sprintf( __( '%1$d units · %2$s', TEXT_DOMAIN ), sum.u, money( sample.symbol, sum.r ) ) }</strong>
			</div>
		</SheetWindow>
	);
};

// ---- Stock rules -----------------------------------------------------------------------------
const StockPreview = ( { sample } ) => {
	const { v } = useAnalyticsSettings();
	const [ sold, setSold ] = useState( 2 );
	const [ stock, setStock ] = useState( 26 );
	const [ idle, setIdle ] = useState( 4 );
	const low = Number( v( 'stock.low_stock_threshold' ) ) || 0;
	const lead = Number( v( 'stock.lead_time' ) ) || 0;
	const safety = Number( v( 'stock.safety_days' ) ) || 0;
	const dead = Number( v( 'stock.dead_stock_days' ) ) || 60;
	const over = Number( v( 'stock.overstock_days' ) ) || 90;
	const cover = sold > 0 ? stock / sold : Infinity;
	const point = Math.ceil( sold * ( lead + safety ) );
	let status = 'healthy';
	if ( stock <= 0 ) {
		status = 'out_of_stock';
	} else if ( idle >= dead ) {
		status = 'dead_stock';
	} else if ( sold > 0 && cover < lead + safety ) {
		status = 'at_risk';
	} else if ( stock < low ) {
		status = 'low_stock';
	} else if ( cover > over ) {
		status = 'overstock';
	}
	const p = sample.products[ 0 ];
	const num = ( id, label, value, set, max ) => (
		<label className="ssgsw-sk__in" htmlFor={ id }>
			<span>{ label }</span>
			<input id={ id } type="number" min="0" max={ max } value={ value } onChange={ ( e ) => set( Math.max( 0, Number( e.target.value ) || 0 ) ) } />
		</label>
	);
	return (
		<div className="ssgsw-sk">
			<div className="ssgsw-sk__head">
				<div>
					<strong>{ p.name }</strong>
					<small>{ p.sku }</small>
				</div>
				<StatusChip status={ status } label={ STATUS_NAMES[ status ] } />
			</div>
			<div className="ssgsw-sk__inputs">
				{ num( 'sk-sold', __( 'Sold per day', TEXT_DOMAIN ), sold, setSold, 99 ) }
				{ num( 'sk-stock', __( 'In stock', TEXT_DOMAIN ), stock, setStock, 9999 ) }
				{ num( 'sk-idle', __( 'Days since last sale', TEXT_DOMAIN ), idle, setIdle, 999 ) }
			</div>
			<div className="ssgsw-sk__stats">
				<div><small>{ __( 'Stock lasts', TEXT_DOMAIN ) }</small><strong>{ Number.isFinite( cover ) ? sprintf( _n( '%d day', '%d days', Math.floor( cover ), TEXT_DOMAIN ), Math.floor( cover ) ) : '–' }</strong></div>
				<div><small>{ __( 'Reorder when stock reaches', TEXT_DOMAIN ) }</small><strong>{ sprintf( _n( '%d unit', '%d units', Number( point ) || 0, TEXT_DOMAIN ), point ) }</strong></div>
			</div>
			<p className="ssgsw-sk__formula">
				{ sprintf( /* translators: 1: sold per day, 2: delivery days, 3: extra days, 4: result */ __( '%1$d sold per day × (%2$d delivery days + %3$d extra days) = %4$d units', TEXT_DOMAIN ), sold, lead, safety, point ) }
			</p>
			{ stock > 0 && stock <= point && sold > 0 && <p className="ssgsw-sk__flag"><Icon name="bell" size={ 14 } /> { __( 'Time to reorder', TEXT_DOMAIN ) }</p> }
		</div>
	);
};

// ---- Forecast and profit ---------------------------------------------------------------------
const ForecastPreview = ( { sample } ) => {
	const { v } = useAnalyticsSettings();
	const on = !! v( 'forecast.enabled' );
	const horizon = Math.max( 7, Math.min( 90, Number( v( 'forecast.horizon' ) ) || 30 ) );
	const trend = v( 'forecast.method' ) === 'holt';
	const alpha = Number( v( 'forecast.alpha' ) ) || 0.3;
	const hist = sample.revenue.slice( -28 );
	const base = hist.slice( -7 ).reduce( ( a, b ) => a + b, 0 ) / 7;
	const W = 360;
	const H = 130;
	const total = 28 + horizon;
	const max = Math.max( ...hist, base * 1.8 ) * 1.1;
	const X = ( i ) => ( i / ( total - 1 ) ) * W;
	const Y = ( val ) => H - 10 - ( val / max ) * ( H - 24 );
	const hp = hist.map( ( val, i ) => `${ i ? 'L' : 'M' }${ X( i ).toFixed( 1 ) } ${ Y( val ).toFixed( 1 ) }` ).join( ' ' );
	const slope = trend ? base * 0.012 : 0;
	const fc = Array.from( { length: horizon + 1 }, ( _, i ) => ( { i: 27 + i, y: base + slope * i, band: base * ( 0.08 + 0.12 * ( 1 - alpha ) ) * Math.sqrt( 1 + i / 6 ) } ) );
	const line = fc.map( ( p, k ) => `${ k ? 'L' : 'M' }${ X( p.i ).toFixed( 1 ) } ${ Y( p.y ).toFixed( 1 ) }` ).join( ' ' );
	const band = `${ fc.map( ( p, k ) => `${ k ? 'L' : 'M' }${ X( p.i ).toFixed( 1 ) } ${ Y( p.y + p.band ).toFixed( 1 ) }` ).join( ' ' ) } ${ [ ...fc ].reverse().map( ( p ) => `L${ X( p.i ).toFixed( 1 ) } ${ Y( Math.max( 0, p.y - p.band ) ).toFixed( 1 ) }` ).join( ' ' ) }Z`;
	// Sample product: 120 units left, selling about base/40 a day.
	const daily = Math.max( 1, base / 40 + ( trend ? 0.4 : 0 ) );
	const left = 120;
	const outDays = Math.floor( left / daily );
	const costKey = v( 'margin.cost_meta_key' );
	const pct = Number( v( 'margin.default_margin_pct' ) ) || 0;
	const price = 40;
	let margin = null;
	if ( costKey ) {
		margin = { cost: 22, profit: ( ( price - 22 ) / price ) * 100, from: sprintf( __( 'Cost read from “%s”', TEXT_DOMAIN ), costKey ) };
	} else if ( pct > 0 ) {
		margin = { cost: price * ( 1 - pct / 100 ), profit: pct, from: __( 'No cost found: using your default margin', TEXT_DOMAIN ) };
	}
	return (
		<>
			<div className={ `ssgsw-fc${ on ? '' : ' is-off' }` }>
				<div className="ssgsw-fc__head"><strong>{ __( 'Forecast', TEXT_DOMAIN ) }</strong><small>{ sprintf( __( 'Next %1$d days · %2$s', TEXT_DOMAIN ), horizon, forecastStyleName( trend ? 'holt' : 'ses' ) ) }</small></div>
				<svg className="ssgsw-fc__svg" viewBox={ `0 0 ${ W } ${ H }` } role="img" aria-label={ __( 'Sample sales forecast', TEXT_DOMAIN ) }>
					<line x1={ X( 27 ) } x2={ X( 27 ) } y1="4" y2={ H - 8 } className="ssgsw-fc__now" />
					<path d={ hp } className="ssgsw-fc__hist" fill="none" />
					{ on && <path d={ band } className="ssgsw-fc__band" /> }
					{ on && <path d={ line } className="ssgsw-fc__line" fill="none" /> }
				</svg>
				<div className="ssgsw-fc__legend"><span><i className="is-hist"></i>{ __( 'Past sales', TEXT_DOMAIN ) }</span><span><i className="is-fc"></i>{ __( 'Forecast', TEXT_DOMAIN ) }</span><span><i className="is-band"></i>{ __( 'Likely range', TEXT_DOMAIN ) }</span></div>
				{ on ? (
					<p className="ssgsw-fc__out"><Icon name="bell" size={ 13 } /> { sprintf( _n( '%1$s runs out in about %2$d day (%3$s)', '%1$s runs out in about %2$d days (%3$s)', outDays, TEXT_DOMAIN ), sample.products[ 0 ].sku, outDays, dayLabel( outDays ) ) }</p>
				) : (
					<p className="ssgsw-fc__out is-muted">{ __( 'Forecast is off', TEXT_DOMAIN ) }</p>
				) }
			</div>
			<div className="ssgsw-mg">
				<div className="ssgsw-mg__head"><strong>{ __( 'Profit', TEXT_DOMAIN ) }</strong><small>{ sample.products[ 0 ].name }</small></div>
				{ margin ? (
					<div className="ssgsw-mg__grid">
						<div><small>{ __( 'Sells for', TEXT_DOMAIN ) }</small><strong>{ money( sample.symbol, price ) }</strong></div>
						<div><small>{ __( 'Costs you', TEXT_DOMAIN ) }</small><strong>{ money( sample.symbol, margin.cost ) }</strong></div>
						<div><small>{ __( 'Profit', TEXT_DOMAIN ) }</small><strong className="is-up">{ margin.profit.toFixed( 0 ) }%</strong></div>
					</div>
				) : <p className="ssgsw-ui-muted">{ __( 'No cost price and no default margin: profit is left empty.', TEXT_DOMAIN ) }</p> }
				{ margin && <p className="ssgsw-mg__from">{ margin.from }</p> }
			</div>
		</>
	);
};

// ---- AI assistant ----------------------------------------------------------------------------
const AiPreview = ( { sample, usage } ) => {
	const { v, meta } = useAnalyticsSettings();
	const provider = v( 'ai.provider' );
	const hasKey = !! ( meta.ai_key && meta.ai_key.set );
	const paused = !! v( 'ai.paused' );
	const names = !! v( 'ai.send_product_names' );
	const limit = Number( v( 'ai.daily_limit' ) ) || 0;
	const used = usage ? Number( usage.used_today ) || 0 : 12;
	const p = sample.products[ 0 ];
	let body;
	if ( ! provider ) {
		body = <div className="ssgsw-ai__empty"><Icon name="ai" size={ 22 } /><strong>{ __( 'Set up AI', TEXT_DOMAIN ) }</strong><span>{ __( 'Pick an AI company in WordPress to ask questions here.', TEXT_DOMAIN ) }</span></div>;
	} else if ( ! hasKey ) {
		body = <div className="ssgsw-ai__empty"><Icon name="lock" size={ 22 } /><strong>{ __( 'Add your AI key', TEXT_DOMAIN ) }</strong><span>{ __( 'Save your key in WordPress to turn the assistant on.', TEXT_DOMAIN ) }</span></div>;
	} else if ( paused || limit === 0 ) {
		body = <div className="ssgsw-ai__empty"><Icon name="info" size={ 22 } /><strong>{ paused ? __( 'The assistant is paused', TEXT_DOMAIN ) : __( 'No questions allowed', TEXT_DOMAIN ) }</strong><span>{ paused ? __( 'Turn “Pause the AI assistant” off to use it again.', TEXT_DOMAIN ) : __( 'Raise the daily question limit to use it.', TEXT_DOMAIN ) }</span></div>;
	} else {
		body = (
			<div className="ssgsw-ai__chat">
				<p className="ssgsw-ai__q">{ __( 'What should I reorder this week?', TEXT_DOMAIN ) }</p>
				<p className="ssgsw-ai__a">
					{ names
						? sprintf( __( 'Reorder %1$s (%2$s) first. It sells about 2 a day and only 18 are left.', TEXT_DOMAIN ), p.name, p.sku )
						: sprintf( __( 'Reorder %s first. It sells about 2 a day and only 18 are left.', TEXT_DOMAIN ), p.sku ) }
				</p>
				<p className="ssgsw-ai__sent"><Icon name={ names ? 'info' : 'lock' } size={ 12 } /> { names ? __( 'Product names are shared with the AI', TEXT_DOMAIN ) : __( 'Only product codes are shared with the AI', TEXT_DOMAIN ) }</p>
			</div>
		);
	}
	const pct = limit ? Math.min( 100, ( used / limit ) * 100 ) : 100;
	return (
		<>
			<SheetWindow menuOpen analyticsMenu tabs={ FS_TABS.slice( 0, 3 ) } activeTab="daily" sidebar={ <SidePanel title={ __( 'Ask AI', TEXT_DOMAIN ) }>{ body }<div className="ssgsw-ai__meter" aria-hidden="true"><span style={ { width: `${ pct }%` } }></span></div><small className="ssgsw-ai__metertxt">{ sprintf( __( '%1$d of %2$d questions used today', TEXT_DOMAIN ), used, limit ) }</small></SidePanel> } sidebarOpen>
				<MiniGrid headers={ SALES_HEAD } rows={ salesRows( sample, 5 ) } num={ [ 3, 4 ] } min={ 6 } />
			</SheetWindow>
			{ v( 'email.enabled' ) && (
				<div className="ssgsw-mail" aria-hidden="true">
					<div className="ssgsw-mail__head"><Icon name="chat" size={ 13 } /><strong>{ __( 'Your daily sales summary', TEXT_DOMAIN ) }</strong><small>{ hh( Number( v( 'email.hour' ) ) || 0 ) }</small></div>
					<p>{ sprintf( __( 'Yesterday: %1$s in sales, 14 orders. %2$s is running low.', TEXT_DOMAIN ), money( sample.symbol, sample.revenue[ sample.revenue.length - 1 ] ), p.sku ) }</p>
				</div>
			) }
		</>
	);
};

// ---- Alerts ----------------------------------------------------------------------------------
const AlertsPreview = ( { sample } ) => {
	const { v, meta } = useAnalyticsSettings();
	const on = !! v( 'alerts.enabled' );
	const email = !! v( 'alerts.channels.email' );
	const slack = !! v( 'alerts.channels.slack' );
	const rules = [
		[ 'stockout', sprintf( __( '%s is out of stock', TEXT_DOMAIN ), sample.products[ 2 ].sku ) ],
		[ 'at_risk', sprintf( __( '%s will run out before your reorder arrives', TEXT_DOMAIN ), sample.products[ 0 ].sku ) ],
		[ 'refund_spike', __( 'Refunds are up this week', TEXT_DOMAIN ) ],
	].filter( ( [ key ] ) => v( `alerts.rules.${ key }` ) );
	const drop = Number( v( 'alerts.rules.sales_drop_pct' ) ) || 0;
	const lines = [ ...rules.map( ( r ) => r[ 1 ] ), ...( drop ? [ sprintf( __( 'Weekly sales are down %d%%', TEXT_DOMAIN ), drop + 5 ) ] : [] ) ];
	const q = /^(\d{2}):(\d{2})-(\d{2}):(\d{2})$/.exec( String( v( 'alerts.quiet_hours' ) || '' ) );
	const from = q ? Number( q[ 1 ] ) + Number( q[ 2 ] ) / 60 : null;
	const to = q ? Number( q[ 3 ] ) + Number( q[ 4 ] ) / 60 : null;
	const quietAt = ( h ) => q && ( from <= to ? h >= from && h < to : h >= from || h < to );
	return (
		<div className={ `ssgsw-al${ on ? '' : ' is-off' }` }>
			{ ! on && <p className="ssgsw-al__off">{ __( 'Alerts are off', TEXT_DOMAIN ) }</p> }
			{ email && (
				<div className="ssgsw-mail" aria-hidden="true">
					<div className="ssgsw-mail__head"><Icon name="bell" size={ 13 } /><strong>{ lines[ 0 ] || __( 'Nothing needs you right now', TEXT_DOMAIN ) }</strong></div>
					<small className="ssgsw-mail__to">{ sprintf( __( 'To: %s', TEXT_DOMAIN ), v( 'alerts.recipients' ) || v( 'email.recipients' ) || meta.admin_email || 'you@yourstore.com' ) }</small>
					<ul>{ lines.map( ( l ) => <li key={ l }>{ l }</li> ) }</ul>
				</div>
			) }
			{ slack && (
				<div className="ssgsw-slack" aria-hidden="true">
					<span className="ssgsw-slack__av">FS</span>
					<div><strong>FlexStock <small>{ __( 'APP', TEXT_DOMAIN ) }</small></strong>{ lines.map( ( l ) => <p key={ l }>{ l }</p> ) }</div>
				</div>
			) }
			{ ! email && ! slack && <p className="ssgsw-ui-muted">{ __( 'Turn on email or Slack to see how an alert looks.', TEXT_DOMAIN ) }</p> }
			<div className="ssgsw-quiet">
				<small>{ q ? sprintf( __( 'Quiet time: %1$s to %2$s', TEXT_DOMAIN ), `${ q[ 1 ] }:${ q[ 2 ] }`, `${ q[ 3 ] }:${ q[ 4 ] }` ) : __( 'Alerts can be sent at any hour', TEXT_DOMAIN ) }</small>
				<div className="ssgsw-quiet__strip" role="img" aria-label={ __( '24 hour strip showing quiet time', TEXT_DOMAIN ) }>
					{ Array.from( { length: 24 }, ( _, h ) => <span key={ h } className={ quietAt( h ) ? 'is-quiet' : '' }></span> ) }
				</div>
				<div className="ssgsw-quiet__scale"><span>0</span><span>6</span><span>12</span><span>18</span><span>24</span></div>
			</div>
		</div>
	);
};

// ---- Vendors and stores ----------------------------------------------------------------------
const VendorsPreview = ( { sample } ) => {
	const { v } = useAnalyticsSettings();
	const vis = v( 'vendors.visibility' );
	const on = !! v( 'vendors.enabled' );
	const heads = [ 'SKU', __( 'Product', TEXT_DOMAIN ), __( 'Units', TEXT_DOMAIN ), ...( vis !== 'units' ? [ __( 'Income', TEXT_DOMAIN ) ] : [] ), ...( vis === 'units_revenue_earnings' ? [ __( 'Earnings', TEXT_DOMAIN ) ] : [] ) ];
	const row = ( p ) => [ p.sku, p.name, String( p.units ), ...( vis !== 'units' ? [ money( sample.symbol, p.revenue ) ] : [] ), ...( vis === 'units_revenue_earnings' ? [ money( sample.symbol, p.revenue * 0.8 ) ] : [] ) ];
	return (
		<div className="ssgsw-two">
			<div>
				<p className="ssgsw-two__label">{ __( 'What a vendor sees in their own sheet', TEXT_DOMAIN ) }</p>
				{ on ? (
					<SheetWindow name={ __( 'Vendor sheet', TEXT_DOMAIN ) } tabs={ FS_TABS.slice( 0, 2 ) } activeTab="daily"><MiniGrid headers={ heads } rows={ sample.products.slice( 0, 3 ).map( row ) } num={ [ 2, 3, 4 ] } min={ 4 } animateKey={ vis } /></SheetWindow>
				) : <p className="ssgsw-ui-muted">{ __( 'Vendors do not see analytics.', TEXT_DOMAIN ) }</p> }
			</div>
			<div>
				<p className="ssgsw-two__label">{ __( 'What you see in your own sheet', TEXT_DOMAIN ) }</p>
				<SheetWindow name={ __( 'Admin sheet', TEXT_DOMAIN ) } tabs={ FS_TABS.slice( 0, 2 ) } activeTab="daily"><MiniGrid headers={ [ 'SKU', __( 'Vendor', TEXT_DOMAIN ), __( 'Units', TEXT_DOMAIN ), __( 'Income', TEXT_DOMAIN ) ] } rows={ sample.products.slice( 0, 3 ).map( ( p, i ) => [ p.sku, [ 'Acme', 'Northwind', 'Globex' ][ i ], String( p.units ), money( sample.symbol, p.revenue ) ] ) } num={ [ 2, 3 ] } min={ 4 } /></SheetWindow>
			</div>
		</div>
	);
};

const StoresPreview = ( { sample } ) => {
	const { v } = useAnalyticsSettings();
	const on = !! v( 'stores.enabled' );
	const t = v( 'stores.collect_time' ) || '00:45';
	const tabs = on ? [ { id: 'all', label: 'All Stores (FS)' }, { id: 'a', label: 'Store A (FS)' }, { id: 'b', label: 'Store B (FS)' } ] : [];
	return (
		<SheetWindow tabs={ tabs } activeTab="all" off={ ! on } offText={ __( 'Connected stores are not included', TEXT_DOMAIN ) }>
			<MiniGrid headers={ [ __( 'Store', TEXT_DOMAIN ), 'SKU', __( 'Units', TEXT_DOMAIN ), __( 'Revenue', TEXT_DOMAIN ) ] } rows={ sample.products.slice( 0, 6 ).map( ( p, i ) => [ i % 2 ? 'Store B' : 'Store A', p.sku, String( p.units ), money( sample.symbol, p.revenue ) ] ) } num={ [ 2, 3 ] } animateKey={ String( on ) } />
			<p className="ssgsw-sw__caption">{ sprintf( __( 'Sales from other stores arrive every day at %s', TEXT_DOMAIN ), t ) }</p>
		</SheetWindow>
	);
};

const PAGES = {
	general: GeneralPreview,
	sync: SyncPreview,
	tabs: TabsPreview,
	orders: OrdersPreview,
	stock: StockPreview,
	forecast: ForecastPreview,
	ai: AiPreview,
	alerts: AlertsPreview,
	vendors: VendorsPreview,
	stores: StoresPreview,
};

/**
 * Live Google Sheet preview. Reads the DRAFT settings (nothing is saved or written) and
 * shows the store's own numbers when they could be fetched, clear sample data otherwise.
 */
export default function SheetPreview( { page, usage } ) {
	const sample = useSample();
	const { v } = useAnalyticsSettings();
	const Body = PAGES[ page ] || GeneralPreview;
	const offNote = page !== 'general' && ! v( 'enabled' ) ? __( 'Sales Analytics is turned off, so your sheet will not show this until you turn it on.', TEXT_DOMAIN ) : '';
	return (
		<PreviewFrame
			caption={ offNote }
			sampleNote={ sample.real ? undefined : __( 'Sample data. Your own numbers appear here once your store has sales.', TEXT_DOMAIN ) }
		>
			<Body sample={ sample } usage={ usage } />
		</PreviewFrame>
	);
}
