package dev.cf.recipe;

import dev.cf.Tones;

import dev.crossfly.ui.*;
import dev.crossfly.ui.color.*;
import dev.crossfly.ui.graphics.*;
import dev.crossfly.ui.layout.*;
import dev.crossfly.ui.style.*;

import static dev.crossfly.ui.Widgets.*;

/**
 * Cards that reflow, and the width check you do not write.
 *
 * <p>Resize the window: one column becomes two, then three. There is no listener here, no
 * {@code if (width > 600)}, and no phone/tablet branch. {@link CardGrid} is told the width a card
 * <i>wants</i> and the column range it may use, and it works the rest out — which means the same
 * code is right on a phone, a tablet, a split-screen window and a desktop nobody tested on.</p>
 *
 * <p>{@link Screen#sizeClass()} exists for the decisions a layout genuinely cannot make: whether to
 * show a second pane at all, whether a table is worth offering. Reach for it there, and not for
 * spacing.</p>
 */
public class R14Reflow extends Recipe
{
   private static final String[] NAME = { "Bearings", "Fasteners", "Seals", "Hydraulics",
      "Electrical", "Tooling", "Adhesives", "Abrasives" };
   private static final int[] COUNT = { 128, 412, 96, 55, 210, 74, 31, 88 };

   private Label sizeLine;

   public String title()
   {
      return "Cards that reflow";
   }

   public String note()
   {
      return "Tell CardGrid the width a card wants, not how many columns to use. Resize the window"
         + " — the reflow is the framework's, not yours.";
   }

   public void build(Component body) throws Exception
   {
      sizeLine = label("", 1f, false, Styles.captionColor, Position.START);
      body.add(LAY_AUTO, outgap(sizeLine, 0, 0, 0, .8f));
      updateSizeLine();
      // Re-read on restyle: a resize repositions, which restyles, so this line follows the window
      // without a resize listener of its own.
      onRestyle(this::updateSizeLine);

      CardGrid grid = new CardGrid().columns(1, 3)
         .cardWidth(13f)
         .gap(.6f);
      grid.testTag("recipe.reflow");
      for (int i = 0; i < NAME.length; i++)
         grid.card(tile(NAME[i], COUNT[i], i));
      body.add(LAY_AUTO, grid);
   }

   private Component tile(String name, int count, int i) throws Exception
   {
      // A grid of cards is exactly where a rotating tone earns its keep: the reflow is the thing
      // being demonstrated, and identical grey tiles make it hard to see that anything moved.
      Card c = Tones.card(Tones.cycle(i));
      c.add(LAY_AUTO, label(name, 1.2f, true, Styles.textColor, Position.START));
      c.add(LAY_AUTO, outgap(label(count + " in stock", 1f, true, Tones.cycle(i),
         Position.START), 0, .2f, 0, 0));
      return c;
   }

   private void updateSizeLine()
   {
      sizeLine.setText("This window is " + Screen.sizeClass() + " — the grid decided the columns,"
         + " nothing here did.");
      sizeLine.setValidLayout(false);
   }
}
