// Left pane — input sections for the FBA calculator

function Inputs({ input, update, mkt, onTitleChange, detecting, templates, applyTemplate }) {
  const { Card: IPCard, Section, Field, NumberInput, TextInput, Select, Slider, Toggle, Pill, ProductGlyph } = window.UI;
  const { CATEGORIES, SIZE_TIERS } = window.FBA;
  const { autoReferral, autoFbaFee, autoStorageMonthly } = window.FBA.calc;

  // Compute auto values for display badges
  const autoRef = (autoReferral(input.category, +input.sellPrice || 0) * 100).toFixed(0);
  const autoFba = autoFbaFee(input.sizeTier).toFixed(2);
  const autoStor = autoStorageMonthly(input.sizeTier).toFixed(2);

  const categoryOptions = Object.entries(CATEGORIES).map(([k, v]) => ({ value: k, label: v.name }));
  const sizeOptions = Object.entries(SIZE_TIERS).map(([k, v]) => ({ value: k, label: v.name, group: v.group }));

  // When user manually changes category/size, mark it as no-longer-auto so we stop overriding from name detection
  const onCategoryChange = (v) => {
    const newPct = autoReferral(v, +input.sellPrice || 0) * 100;
    update({
      category: v,
      referralPct: +newPct.toFixed(2),
      autoDetected: { ...(input.autoDetected || {}), category: false },
    });
  };
  const onSizeChange = (v) => {
    update({
      sizeTier: v,
      fbaFee: autoFbaFee(v),
      storageMonthly: autoStorageMonthly(v),
      weight: SIZE_TIERS[v]?.weight ?? input.weight,
      autoDetected: { ...(input.autoDetected || {}), sizeTier: false },
    });
  };
  const onSellChange = (v) => {
    const cat = CATEGORIES[input.category];
    let newPct = input.referralPct;
    if (cat?.threshold) {
      newPct = autoReferral(input.category, +v || 0) * 100;
    }
    update({ sellPrice: v, referralPct: +(+newPct).toFixed(2) });
  };

  const catDetected = input.autoDetected?.category && !!input.category;
  const sizeDetected = input.autoDetected?.sizeTier && !!input.sizeTier;

  return (
    <div className="inputs-pane">
      {/* ─────────── Product ─────────── */}
      <Section title="Product" icon={<IconBox />} kicker="Name it — we'll detect category & size" defaultOpen={true}>
        <div className="product-head">
          <div className="product-glyph-wrap">
            <ProductGlyph kind={input.image || "box"} size={68} />
          </div>
          <div className="product-meta">
            <Field
              label="Product name"
              sublabel="Put product name"
              full
              hint={detecting
                ? "Detecting category from your product name…"
                : (catDetected
                    ? `✓ Auto-detected as ${CATEGORIES[input.category]?.name}${sizeDetected ? " · " + SIZE_TIERS[input.sizeTier]?.group : ""}`
                    : "Type a descriptive product name to auto-detect category & fees")}
            >
              <TextInput
                value={input.title}
                onChange={v => onTitleChange ? onTitleChange(v) : update({ title: v })}
                placeholder="e.g. Stainless Steel Insulated Water Bottle"
              />
            </Field>
            {templates && templates.length > 0 && (
              <div className="tmpl-chips">
                <span className="tmpl-chips-label">Quick start:</span>
                {templates.slice(0, 6).map(t => (
                  <button key={t.slug} className="tmpl-chip" onClick={() => applyTemplate(t.slug)}>
                    {t.label}
                  </button>
                ))}
              </div>
            )}
          </div>
        </div>

        <div className="field-grid two">
          <Field label="Category" auto={catDetected} hint={catDetected ? "Auto-detected from product name — change to override" : "Drives referral fee %"}>
            <Select value={input.category} onChange={onCategoryChange} options={categoryOptions} />
          </Field>
          <Field label="Size tier" auto={sizeDetected} hint={sizeDetected ? "Auto-detected from product name — change to override" : "Drives FBA & storage fees"}>
            <Select value={input.sizeTier} onChange={onSizeChange} options={sizeOptions} groupBy />
          </Field>
        </div>

        <div className="field-grid four">
          <Field label="Weight" suffix="lb">
            <NumberInput value={input.weight} onChange={v => update({ weight: v })} step={0.1} min={0} />
          </Field>
          <Field label="Length" suffix="in">
            <NumberInput value={input.length} onChange={v => update({ length: v })} step={0.1} min={0} />
          </Field>
          <Field label="Width" suffix="in">
            <NumberInput value={input.width} onChange={v => update({ width: v })} step={0.1} min={0} />
          </Field>
          <Field label="Height" suffix="in">
            <NumberInput value={input.height} onChange={v => update({ height: v })} step={0.1} min={0} />
          </Field>
        </div>
      </Section>

      {/* ─────────── Costs ─────────── */}
      <Section title="Sourcing & inbound" icon={<IconTruck />} kicker="Landed cost per unit">
        <div className="field-grid two">
          <Field label="Unit cost (COGS)" prefix={mkt.symbol}>
            <NumberInput value={input.unitCost} onChange={v => update({ unitCost: v })} step={0.01} min={0} />
          </Field>
          <Field label="Inbound shipping per unit" prefix={mkt.symbol}>
            <NumberInput value={input.shippingPerUnit} onChange={v => update({ shippingPerUnit: v })} step={0.01} min={0} />
          </Field>
          <Field label="Prep & inspection per unit" prefix={mkt.symbol}>
            <NumberInput value={input.prepPerUnit} onChange={v => update({ prepPerUnit: v })} step={0.01} min={0} />
          </Field>
          <Field label="Duty / customs" suffix="% of COGS">
            <NumberInput value={input.dutyPct} onChange={v => update({ dutyPct: v })} step={0.5} min={0} max={100} />
          </Field>
        </div>
        <Field label="Order quantity" hint="Used for break-even and cash-flow projections" full>
          <NumberInput value={input.orderQty} onChange={v => update({ orderQty: v })} step={50} min={1} />
        </Field>
      </Section>

      {/* ─────────── Pricing ─────────── */}
      <Section title="Pricing" icon={<IconTag />} kicker="What buyers pay">
        <div className="field-grid two">
          <Field label="Sell price" prefix={mkt.symbol}>
            <NumberInput value={input.sellPrice} onChange={onSellChange} step={0.01} min={0} />
          </Field>
          <Field label="Coupon / promo" suffix="% off">
            <NumberInput value={input.discountPct} onChange={v => update({ discountPct: v })} step={1} min={0} max={90} />
          </Field>
        </div>
      </Section>

      {/* ─────────── Amazon fees ─────────── */}
      <Section title="Amazon fees" icon={<IconAmazon />} kicker={`Auto: ${autoRef}% ref · ${mkt.symbol}${autoFba} FBA`} badge="auto">
        <div className="field-grid two">
          <Field label="Referral fee" suffix="%" auto>
            <NumberInput value={input.referralPct} onChange={v => update({ referralPct: v })} step={0.5} min={0} max={45} />
          </Field>
          <Field label="FBA fulfillment fee" prefix={mkt.symbol} auto>
            <NumberInput value={input.fbaFee} onChange={v => update({ fbaFee: v })} step={0.05} min={0} />
          </Field>
          <Field label="Monthly storage" prefix={mkt.symbol} suffix="/ unit / mo" auto>
            <NumberInput value={input.storageMonthly} onChange={v => update({ storageMonthly: v })} step={0.05} min={0} />
          </Field>
          <Field label="Months in storage" suffix="mo">
            <NumberInput value={input.monthsInStorage} onChange={v => update({ monthsInStorage: v })} step={0.5} min={0} />
          </Field>
          <Field label="Long-term storage" prefix={mkt.symbol} suffix="/ unit" hint="If sitting >365 days">
            <NumberInput value={input.longTermStorage} onChange={v => update({ longTermStorage: v })} step={0.05} min={0} />
          </Field>
        </div>
      </Section>

      {/* ─────────── Marketing ─────────── */}
      <Section title="Advertising (PPC)" icon={<IconMegaphone />} kicker="Sponsored ads cost · Industry avg 25–35% ACoS">
        <div className="field-grid two">
          <Field label="ACoS" suffix="%" hint="Industry avg 25–35% · Strong listings 10–20% · Launch 40–60%">
            <NumberInput value={input.acosPct} onChange={v => update({ acosPct: v })} step={1} min={0} max={150} />
          </Field>
          <Field label="% of sales from PPC" suffix="%" hint="Industry avg 20–40% · New launches 70–90% · 0% if fully organic">
            <NumberInput value={input.ppcSharePct} onChange={v => update({ ppcSharePct: v })} step={5} min={0} max={100} />
          </Field>
        </div>
      </Section>

      {/* ─────────── Other costs ─────────── */}
      <Section title="Returns & taxes" icon={<IconReceipt />} kicker="Refunds, VAT, handling">
        <div className="field-grid two">
          <Field label="Return rate" suffix="%" hint="Defaults to 2% — industry avg 2–8%">
            <NumberInput value={input.returnRatePct} onChange={v => update({ returnRatePct: v })} step={0.5} min={0} max={50} />
          </Field>
          <Field label="Return handling cost" prefix={mkt.symbol} suffix="/ returned unit">
            <NumberInput value={input.returnHandlingCost} onChange={v => update({ returnHandlingCost: v })} step={0.25} min={0} />
          </Field>
          <Field label={`VAT / GST (${mkt.code})`} suffix="%" auto full>
            <NumberInput value={input.vatPct} onChange={v => update({ vatPct: v })} step={0.5} min={0} max={50} />
          </Field>
        </div>
      </Section>

      {/* ─────────── Projection ─────────── */}
      <Section title="Sales velocity" icon={<IconChart />} kicker="Units / day for projections">
        <Field label="Estimated daily sales" hint="Drag the slider or type an exact number — drives monthly & annual projections and break-even days" full>
          <Slider value={+input.unitsPerDay || 0} onChange={v => update({ unitsPerDay: v })} min={0} max={1000} step={1} suffix=" units/day" editable />
        </Field>
      </Section>
    </div>
  );
}

// ── Minimal icon set ──
function IconBox() { return <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M3 7l9-4 9 4-9 4-9-4z"/><path d="M3 7v10l9 4 9-4V7"/><path d="M12 11v10"/></svg>; }
function IconTruck() { return <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><rect x="2" y="6" width="13" height="10" rx="1"/><path d="M15 9h4l3 3v4h-7"/><circle cx="6.5" cy="18" r="2"/><circle cx="18" cy="18" r="2"/></svg>; }
function IconTag() { return <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M3 12l9-9h8v8l-9 9z"/><circle cx="15.5" cy="8.5" r="1.5"/></svg>; }
function IconAmazon() { return <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M4 17c4 3 12 3 16 0"/><path d="M18 14c0 0 1 2 3 3"/><circle cx="10" cy="9" r="3"/></svg>; }
function IconMegaphone() { return <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M3 11v2l13 5V6L3 11z"/><path d="M16 9a3 3 0 010 6"/></svg>; }
function IconReceipt() { return <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M5 3v18l3-2 3 2 3-2 3 2 3-2V3z"/><path d="M8 8h8M8 12h8M8 16h5"/></svg>; }
function IconChart() { return <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M3 20h18"/><path d="M6 16V9M11 16V5M16 16v-8M21 16v-4"/></svg>; }

window.Inputs = Inputs;
