/* Shared navigation for the live, advisory competitor-pricing workspace. */
function CompetitorPricingNav() {
  const { screen, screenState = {}, setScreen } = window.useOffice();
  const active = screen === "priceDetail" ? screenState.priceFrom || "pricing" : screen;
  return <nav className="off-pricing-tabs" aria-label="Competitor pricing">
    {[["pricing","To review"],["pricingBreakdown","Category & brand"],["pricePosition","Market position"],["pricingChecks","Checks"],["pricingRegister","KVI register"],["pricingMethods","Rules & methods"]].map(([key,label]) =>
      <button key={key} aria-current={active === key ? "page" : undefined} onClick={() => setScreen(key)}>{label}</button>)}
  </nav>;
}

function CompetitorPricingHeader({copyRows} = {}) {
  const { stores = [], activeStoreId } = window.useOffice();
  const store = stores.find(s => s.id === activeStoreId);
  const [capture, setCapture] = React.useState(false);
  const [copying, setCopying] = React.useState(false);
  const [message, setMessage] = React.useState(null);
  const [copyText, setCopyText] = React.useState(null);
  const refresh = () => window.dispatchEvent(new Event("office-pricing-refresh"));
  const copy = async () => {
    setCopying(true); setMessage(null);
    try {
      const data = copyRows?.length ? {rows:copyRows,generatedAt:new Date().toISOString()} : await window.OfficeAPI.pricingQueue();
      const clean = v => String(v == null ? "" : v).replace(/[\t\r\n]/g," ");
      const text = [["Advisory recommendations", "Generated", data.generatedAt], ["Product","SKU","Current ($)","Recommended ($)","Reason"], ...data.rows.map(r => [r.name,r.sku,r.currentCents == null ? "" : (r.currentCents/100).toFixed(2),r.recommendedCents == null ? "" : (r.recommendedCents/100).toFixed(2),r.reasonDetail])].map(row => row.map(clean).join("\t")).join("\n");
      if (navigator.clipboard && navigator.clipboard.writeText) { await navigator.clipboard.writeText(text); setMessage("Copied " + data.rows.length + " advisory row" + (data.rows.length===1 ? "" : "s") + ". Shelf prices are unchanged."); }
      else { setCopyText(text); }
    } catch (e) { setMessage(e.message || "Couldn't copy the pricing list."); }
    finally { setCopying(false); }
  };
  return <>
    <header className="off-screen-header off-pricing-header">
      <div className="off-screen-header-meta">
        <span className="off-screen-eyebrow">Pricing{store ? " · " + store.name : " · current organisation"}</span>
        <h2 className="off-screen-title">Competitor pricing</h2>
        <p className="off-pricing-subtitle">Observed prices in, recommendations out. Each store runs its own method, and every number carries the working behind it.</p>
      </div>
      <div className="off-pricing-actions">
        <button className="btn btn--ghost btn--sm" disabled={copying} onClick={copy}><window.OIcon name="download" /> {copying ? "Copying…" : "Copy list"}</button>
        <button className="btn btn--secondary btn--sm" onClick={() => { setCapture(true); refresh(); }}><window.OIcon name="refresh" /> Recapture prices</button>
      </div>
    </header>
    <CompetitorPricingNav />
    {message && <div className="off-pricing-header-message" role="status">{message}<button className="btn btn--ghost btn--sm" onClick={() => setMessage(null)}>Dismiss</button></div>}
    {(capture || copyText) && <div className="off-pricing-modal-backdrop"><section className="off-pricing-modal off-card" role="dialog" aria-modal="true" aria-label={capture ? "Recapture competitor price" : "Copy pricing list"}>
      <div className="off-pricing-section-head"><h3 className="off-card-title">{capture ? "Capture an observed competitor price" : "Copy advisory recommendations"}</h3><button className="btn btn--ghost btn--sm" onClick={() => {setCapture(false);setCopyText(null);}}>Close</button></div>
      {capture ? <><p className="off-pricing-intro">Enter a price you have checked. The existing automated feed runs separately.</p><window.CompetitorCaptureForm compact onSaved={() => {setCapture(false);refresh();setMessage("Competitor price saved. Recommendations refreshed.");}} onCancel={() => setCapture(false)} /></> : <textarea className="off-input" readOnly aria-label="Advisory pricing list" value={copyText} onFocus={e => e.target.select()} />}
    </section></div>}
  </>;
}

window.CompetitorPricingNav = CompetitorPricingNav;
window.CompetitorPricingHeader = CompetitorPricingHeader;

function PricingScopeDisclosure({ children }) {
  return <details className="off-pricing-disclosure"><summary>How these figures are calculated</summary><div>{children}</div></details>;
}
window.PricingScopeDisclosure = PricingScopeDisclosure;
