/* Ingredient tree — recursive expansion */

const { useState: useStateT, useMemo: useMemoT } = React;

function IngredientRow({ mat, scale, depth, ctx, choices, priceOverrides, expansion, onToggleExpand, onToggleMode, onPriceChange, onResetPrice, onJumpToRecipe, currency, parentKey }) {
  const qty = mat.amount * scale;
  const key = mat.itemType;
  const expKey = parentKey + '>' + key;
  const subRecipe = getRecipeFor(key, ctx);
  const canCraft = !!subRecipe && depth < 6;
  const expanded = expansion[expKey] === true;

  const threshold = ctx.laborThreshold ?? 0;
  const choice = (choices[key] || window.defaultModeFor(key, qty, subRecipe, canCraft, ctx, choices, priceOverrides, depth, new Set(), threshold));
  const marketPrice = ctx.prices[key];
  const overridePrice = priceOverrides[key];
  const effectivePrice = overridePrice != null ? overridePrice : (marketPrice ?? 0);

  let unitCostShown = effectivePrice;
  let subtotal = effectivePrice * qty;
  let subTally = null;

  if (choice === 'craft' && canCraft) {
    subTally = tally(subRecipe, choices, priceOverrides, ctx, { scale: qty / subRecipe.productCount, depth: depth + 1, visited: new Set() });
    unitCostShown = qty > 0 ? subTally.cost / qty : 0;
    subtotal = subTally.cost;
  }

  const initial = initialFor(mat.name);

  return (
    <>
      <div className={`ing-row ${depth > 0 ? `depth-${Math.min(depth, 3)}` : ''}`}>
        <div className="ing-name">
          <span className="ing-indent" style={{ width: depth * 22 }} />
          {depth > 0 && <span className="tree-connector">└</span>}
          <button
            className={`expand-btn ${canCraft ? '' : 'empty'} ${expanded ? 'open' : ''}`}
            onClick={() => canCraft && onToggleExpand(expKey)}
            title={canCraft ? 'Show sub-recipe' : ''}
          >▸</button>
          <div className="ing-chip-wrap"><window.ItemIcon itemType={key} name={mat.name} size="sm" /></div>
          <div style={{minWidth: 0}}>
            <div className="ing-label">
              {canCraft && onJumpToRecipe ? (
                <button
                  type="button"
                  className="ing-jump"
                  title={`Open ${mat.name} crafting recipe`}
                  onClick={(e) => { e.stopPropagation(); onJumpToRecipe(key); }}
                >
                  {mat.name}
                  <span className="ing-jump-arrow" aria-hidden="true">↗</span>
                </button>
              ) : (
                mat.name
              )}
            </div>
            <div className="ing-meta">
              {marketPrice == null && choice !== 'craft' && <span className="nomarket">no market price</span>}
              {marketPrice == null && choice === 'craft' && <span className="craftable">crafted</span>}
              {marketPrice != null && choice === 'craft' && <span className="craftable">crafted ({fmtG(marketPrice)}g market)</span>}
              {marketPrice != null && choice !== 'craft' && canCraft && <span className="craftable">recipe available</span>}
              {(() => {
                const vol = ctx.volumes && ctx.volumes[key];
                if (vol == null) return null;
                const unit = vol.p === 'week' ? '/wk' : '/day';
                const label = vol.p === 'week' ? 'Weekly' : 'Daily';
                return (
                  <span className={`vol-tag mini ${vol.p === 'week' ? 'weekly' : ''}`} title={`${label} auction volume: ${window.fmtInt(vol.v)} units${unit === '/wk' ? '/week' : '/day'}`}>
                    <span className="vol-ico">↻</span>{window.fmtCompact(vol.v)}{unit}
                  </span>
                );
              })()}
            </div>
          </div>
        </div>

        <div className="qty-cell">×{fmtInt(qty)}</div>

        <div className="price-cell">
          {canCraft && (
            <span className="mode-toggle">
              <button className={`m ${choice === 'market' ? 'on' : ''}`} onClick={() => onToggleMode(key, 'market')} disabled={marketPrice == null && overridePrice == null}>Buy</button>
              <button className={`c ${choice === 'craft' ? 'on' : ''}`} onClick={() => onToggleMode(key, 'craft')}>Craft</button>
            </span>
          )}
          {choice === 'craft' && canCraft ? (
            <span style={{display:'inline-flex', alignItems:'baseline', gap:6, flexWrap:'wrap', justifyContent:'flex-end'}}>
              <span style={{fontFamily: 'var(--mono)', color: 'var(--sapphire)', fontSize: 12}}>
                {fmtG(unitCostShown)}{currency}
              </span>
              {(() => {
                if (!subTally || marketPrice == null) return null;
                if (subTally.labor <= 0) return null;
                const savings = marketPrice * qty - subTally.cost;
                const gpl = savings / subTally.labor;
                const meets = gpl >= threshold;
                return (
                  <span
                    className={`craft-gpl ${meets ? 'good' : 'bad'}`}
                    title={`${fmtG(savings)}${currency} saved over buying · ${fmtInt(subTally.labor)} labor spent · threshold ${threshold}${currency}/lp`}
                  >
                    {gpl >= 0 ? '+' : '−'}{fmtG(Math.abs(gpl))}{currency}/lp
                  </span>
                );
              })()}
            </span>
          ) : (
            <span className={`price-edit ${overridePrice != null ? 'modified' : ''}`}>
              <input
                type="number"
                step="0.01"
                value={effectivePrice}
                min="0"
                onChange={(e) => onPriceChange(key, e.target.value === '' ? 0 : Number(e.target.value))}
              />
              <span className="cur">{currency}</span>
            </span>
          )}
          {overridePrice != null && choice !== 'craft' && (
            <span className="price-reset" onClick={() => onResetPrice(key)}>↺</span>
          )}
        </div>

        <div className="subtotal-cell">
          {fmtG(subtotal)}{currency}
        </div>
      </div>

      {expanded && canCraft && (
        <>
          {subRecipe.laborCost > 0 && (
            <div className={`ing-row depth-${Math.min(depth + 1, 3)}`} style={{padding: '8px 14px', fontSize: 11}}>
              <div className="ing-name">
                <span className="ing-indent" style={{ width: (depth + 1) * 22 }} />
                <span className="tree-connector">└</span>
                <span style={{ width: 18 }} />
                <div className="ing-chip" style={{background: 'rgba(230,179,112,0.12)', borderColor: 'rgba(230,179,112,0.35)', color: 'var(--labor)'}}>LP</div>
                <div>
                  <div className="ing-label" style={{color: 'var(--labor)'}}>Labor</div>
                  <div className="ing-meta">{fmtInt(subRecipe.laborCost * qty / subRecipe.productCount)} points · sub-craft</div>
                </div>
              </div>
              <div className="qty-cell" style={{color: 'var(--labor)'}}>{fmtInt(qty / subRecipe.productCount)}×</div>
              <div className="price-cell" style={{color: 'var(--labor)', fontSize: 11, fontFamily: 'var(--mono)'}}>
                {subRecipe.laborCost} lp / craft
              </div>
              <div className="subtotal-cell" style={{color: 'var(--labor)'}}>
                —
              </div>
            </div>
          )}
          {subRecipe.materials.map((subMat, i) => (
            <IngredientRow
              key={expKey + '>' + i + ':' + subMat.itemType}
              mat={subMat}
              scale={qty / subRecipe.productCount}
              depth={depth + 1}
              ctx={ctx}
              choices={choices}
              priceOverrides={priceOverrides}
              expansion={expansion}
              onToggleExpand={onToggleExpand}
              onToggleMode={onToggleMode}
              onPriceChange={onPriceChange}
              onResetPrice={onResetPrice}
              onJumpToRecipe={onJumpToRecipe}
              currency={currency}
              parentKey={expKey}
            />
          ))}
        </>
      )}
    </>
  );
}

window.IngredientRow = IngredientRow;
