unit frm_HorneadoGrafica;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes,
  Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.StdCtrls,
  Vcl.Buttons, Vcl.ComCtrls, Vcl.Grids, Vcl.DBGrids, Vcl.Clipbrd, Data.DB,
  FireDAC.Comp.Client, FireDAC.Stan.Param, FireDAC.Stan.Option, System.Math, System.DateUtils,
  System.UITypes, System.Types;

type
  TTempReading = record
    FechaHora: TDateTime;
    TempAmbiente: Double;
    Zona1Temp: Double;
    HasAmbiente: Boolean;
    HasZona1: Boolean;
    Masa: string;
    Carro: string;
    Dispositivo: string;
    Bateria: Integer;
  end;

  TfrmHorneadoGrafica = class(TForm)
    pnlHeader: TPanel;
    pnlHeaderContent: TPanel;
    lblTitle: TLabel;
    lblSubTitle: TLabel;
    pnlKpis: TPanel;
    pnlKpiHorno: TPanel;
    lblKpiHornoTitle: TLabel;
    lblKpiHornoVal: TLabel;
    pnlKpiCorazon: TPanel;
    lblKpiCorazonTitle: TLabel;
    lblKpiCorazonVal: TLabel;
    pnlKpiContexto: TPanel;
    lblKpiContextoTitle: TLabel;
    lblKpiContextoVal: TLabel;
    pnlKpiDuracion: TPanel;
    lblKpiDuracionTitle: TLabel;
    lblKpiDuracionVal: TLabel;
    pgcMain: TPageControl;
    tsGrafica: TTabSheet;
    pnlChartLegend: TPanel;
    lblLegendAmb: TLabel;
    lblLegendZ1: TLabel;
    lblChartHelp: TLabel;
    pnlChartContainer: TPanel;
    pbChart: TPaintBox;
    tsLecturas: TTabSheet;
    dbGridLecturas: TDBGrid;
    pnlFooter: TPanel;
    btnExportarCsv: TSpeedButton;
    btnCopiar: TSpeedButton;
    btnCerrar: TSpeedButton;
    qryLecturas: TFDQuery;
    dsLecturas: TDataSource;

    procedure FormCreate(Sender: TObject);
    procedure FormDestroy(Sender: TObject);
    procedure FormShow(Sender: TObject);
    procedure FormResize(Sender: TObject);
    procedure pbChartPaint(Sender: TObject);
    procedure pbChartMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
    procedure btnCerrarClick(Sender: TObject);
    procedure btnExportarCsvClick(Sender: TObject);
    procedure btnCopiarClick(Sender: TObject);
  private
    FLoteId: Integer;
    FLoteCodigo: string;
    FArticuloDesc: string;
    FReadings: TArray<TTempReading>;
    FHoverIndex: Integer;

    procedure CargarDatos;
    procedure CalcularEstadisticas;
    procedure ConfigurarColumnasGrid;
  public
    class procedure MostrarParaLote(
      AOwner: TComponent;
      ALoteId: Integer;
      const ALoteCodigo: string;
      const AArticuloDesc: string = ''
    );
  end;

var
  frmHorneadoGrafica: TfrmHorneadoGrafica;

implementation

uses
  dmg_Main, uAppTheme;

{$R *.dfm}

{ TfrmHorneadoGrafica }

class procedure TfrmHorneadoGrafica.MostrarParaLote(
  AOwner: TComponent;
  ALoteId: Integer;
  const ALoteCodigo: string;
  const AArticuloDesc: string
);
var
  QryCheck: TFDQuery;
  LCount: Integer;
  LDlg: TfrmHorneadoGrafica;
  LCodigo: string;
begin
  LCodigo := Trim(ALoteCodigo);
  if (ALoteId <= 0) and (LCodigo = '') then
  begin
    MessageDlg('No se ha especificado un lote válido para consultar su horneado.', mtWarning, [mbOk], 0);
    Exit;
  end;

  // 1. Comprobar previamente si existen datos en ge_temperaturas_log
  QryCheck := TFDQuery.Create(nil);
  try
    QryCheck.Connection := dmgMain.dbConn;
    QryCheck.SQL.Text :=
      'SELECT COUNT(*) as cnt ' +
      'FROM ge_temperaturas_log ' +
      'WHERE (id_lote = :id_lote AND :id_lote > 0) OR (:lote_cod <> '''' AND lote_codigo = :lote_cod)';
    QryCheck.ParamByName('id_lote').AsInteger := ALoteId;
    QryCheck.ParamByName('lote_cod').DataType := ftWideString;
    QryCheck.ParamByName('lote_cod').AsWideString := LCodigo;
    QryCheck.Open;

    LCount := QryCheck.FieldByName('cnt').AsInteger;
  finally
    QryCheck.Free;
  end;

  if LCount = 0 then
  begin
    MessageDlg(
      Format(
        'No se han encontrado registros de horneado para el Lote %s (ID: %d).' + sLineBreak + sLineBreak +
        'Compruebe que el termómetro digital MeatMeet Pro estuvo vinculado a este lote durante el proceso de horneado.',
        [LCodigo, ALoteId]
      ),
      mtInformation,
      [mbOk],
      0
    );
    Exit;
  end;

  // 2. Abrir formulario modal
  LDlg := TfrmHorneadoGrafica.Create(AOwner);
  try
    LDlg.FLoteId := ALoteId;
    LDlg.FLoteCodigo := LCodigo;
    LDlg.FArticuloDesc := Trim(AArticuloDesc);
    LDlg.CargarDatos;
    LDlg.ShowModal;
  finally
    LDlg.Free;
  end;
end;

procedure TfrmHorneadoGrafica.FormCreate(Sender: TObject);
begin
  FHoverIndex := -1;
  SetLength(FReadings, 0);
  qryLecturas.Connection := dmgMain.dbConn;
  qryLecturas.FetchOptions.Mode := fmAll;
  qryLecturas.FetchOptions.RowsetSize := 2000;
end;

procedure TfrmHorneadoGrafica.FormDestroy(Sender: TObject);
begin
  qryLecturas.Close;
  SetLength(FReadings, 0);
end;

procedure TfrmHorneadoGrafica.FormShow(Sender: TObject);
begin
  FormResize(nil);
  if Assigned(pbChart) then
    pbChart.Invalidate;
end;

procedure TfrmHorneadoGrafica.FormResize(Sender: TObject);
var
  LKpiW, LTotalW, LGap: Integer;
begin
  if not Assigned(pnlKpis) then Exit;

  LTotalW := pnlHeaderContent.Width;
  LGap := 8;
  LKpiW := Max(180, (LTotalW - (LGap * 3)) div 4);

  pnlKpiHorno.Left := 0;
  pnlKpiHorno.Width := LKpiW;

  pnlKpiCorazon.Left := LKpiW + LGap;
  pnlKpiCorazon.Width := LKpiW;

  pnlKpiContexto.Left := (LKpiW + LGap) * 2;
  pnlKpiContexto.Width := LKpiW;

  pnlKpiDuracion.Left := (LKpiW + LGap) * 3;
  pnlKpiDuracion.Width := LTotalW - pnlKpiDuracion.Left;
end;

procedure TfrmHorneadoGrafica.CargarDatos;
var
  LSql: string;
  R: TTempReading;
  LDisp: string;
begin
  qryLecturas.Close;
  LSql :=
    'SELECT ' +
    '  t.id, ' +
    '  t.fecha_hora, ' +
    '  t.temp_ambiente, ' +
    '  t.zona1_temp, ' +
    '  t.zona2_temp, ' +
    '  t.zona3_temp, ' +
    '  t.zona4_temp, ' +
    '  t.zona5_temp, ' +
    '  t.numero_masa, ' +
    '  t.numero_carro, ' +
    '  t.bateria, ' +
    '  t.dispositivo, ' +
    '  t.operador, ' +
    '  t.observaciones ' +
    'FROM ge_temperaturas_log t ' +
    'WHERE (t.id_lote = :id_lote AND :id_lote > 0) ' +
    '   OR (:lote_cod <> '''' AND t.lote_codigo = :lote_cod) ' +
    'ORDER BY t.fecha_hora ASC, t.id ASC';

  qryLecturas.SQL.Text := LSql;
  qryLecturas.ParamByName('id_lote').AsInteger := FLoteId;
  qryLecturas.ParamByName('lote_cod').DataType := ftWideString;
  qryLecturas.ParamByName('lote_cod').AsWideString := FLoteCodigo;
  qryLecturas.Open;
  qryLecturas.FetchAll;

  SetLength(FReadings, 0);
  LDisp := '';

  qryLecturas.First;
  while not qryLecturas.Eof do
  begin
    R.FechaHora := qryLecturas.FieldByName('fecha_hora').AsDateTime;
    R.HasAmbiente := not qryLecturas.FieldByName('temp_ambiente').IsNull;
    if R.HasAmbiente then
      R.TempAmbiente := qryLecturas.FieldByName('temp_ambiente').AsFloat
    else
      R.TempAmbiente := 0.0;

    R.HasZona1 := not qryLecturas.FieldByName('zona1_temp').IsNull;
    if R.HasZona1 then
      R.Zona1Temp := qryLecturas.FieldByName('zona1_temp').AsFloat
    else
      R.Zona1Temp := 0.0;

    R.Masa := Trim(qryLecturas.FieldByName('numero_masa').AsString);
    R.Carro := Trim(qryLecturas.FieldByName('numero_carro').AsString);
    R.Dispositivo := Trim(qryLecturas.FieldByName('dispositivo').AsString);
    if (LDisp = '') and (R.Dispositivo <> '') then
      LDisp := R.Dispositivo;

    if not qryLecturas.FieldByName('bateria').IsNull then
      R.Bateria := qryLecturas.FieldByName('bateria').AsInteger
    else
      R.Bateria := 0;

    SetLength(FReadings, Length(FReadings) + 1);
    FReadings[High(FReadings)] := R;
    qryLecturas.Next;
  end;
  qryLecturas.First;

  // Título e información
  lblTitle.Caption := Format('🔥 Curva de Horneado — Lote: %s (ID: %d)', [FLoteCodigo, FLoteId]);
  if FArticuloDesc <> '' then
    lblSubTitle.Caption := Format('Producto: %s  |  Dispositivo: %s  |  %d lecturas registradas', [FArticuloDesc, LDisp, Length(FReadings)])
  else
    lblSubTitle.Caption := Format('Dispositivo: %s  |  %d lecturas registradas', [LDisp, Length(FReadings)]);

  CalcularEstadisticas;
  ConfigurarColumnasGrid;
end;

procedure TfrmHorneadoGrafica.CalcularEstadisticas;
var
  I: Integer;
  LMinAmb, LMaxAmb, LSumAmb: Double;
  LMinZ1, LMaxZ1: Double;
  LCountAmb, LCountZ1: Integer;
  LInicio, LFin: TDateTime;
  LDiffSeg, LMinutos, LSegundos: Integer;
  LMasas, LCarros: TStringList;
  SMasas, SCarros: string;
begin
  if Length(FReadings) = 0 then Exit;

  LMinAmb := 999.0;
  LMaxAmb := -999.0;
  LSumAmb := 0.0;
  LCountAmb := 0;

  LMinZ1 := 999.0;
  LMaxZ1 := -999.0;
  LCountZ1 := 0;

  LInicio := FReadings[0].FechaHora;
  LFin := FReadings[High(FReadings)].FechaHora;

  LMasas := TStringList.Create;
  LCarros := TStringList.Create;
  try
    LMasas.Duplicates := dupIgnore;
    LMasas.Sorted := True;
    LCarros.Duplicates := dupIgnore;
    LCarros.Sorted := True;

    for I := 0 to High(FReadings) do
    begin
      if FReadings[I].HasAmbiente then
      begin
        LMinAmb := Min(LMinAmb, FReadings[I].TempAmbiente);
        LMaxAmb := Max(LMaxAmb, FReadings[I].TempAmbiente);
        LSumAmb := LSumAmb + FReadings[I].TempAmbiente;
        Inc(LCountAmb);
      end;

      if FReadings[I].HasZona1 then
      begin
        LMinZ1 := Min(LMinZ1, FReadings[I].Zona1Temp);
        LMaxZ1 := Max(LMaxZ1, FReadings[I].Zona1Temp);
        Inc(LCountZ1);
      end;

      if FReadings[I].Masa <> '' then
        LMasas.Add(FReadings[I].Masa);
      if FReadings[I].Carro <> '' then
        LCarros.Add(FReadings[I].Carro);
    end;

    // KPI 1: Horno
    if LCountAmb > 0 then
      lblKpiHornoVal.Caption := Format('%.1f °C  (Avg: %.1f °C)', [LMaxAmb, LSumAmb / LCountAmb])
    else
      lblKpiHornoVal.Caption := 'Sin datos';

    // KPI 2: Corazón
    if LCountZ1 > 0 then
      lblKpiCorazonVal.Caption := Format('%.1f °C  (Mín: %.1f °C)', [LMaxZ1, LMinZ1])
    else
      lblKpiCorazonVal.Caption := 'Sin datos';

    // KPI 3: Contexto Masa y Carro
    SMasas := StringReplace(LMasas.CommaText, '"', '', [rfReplaceAll]);
    SCarros := StringReplace(LCarros.CommaText, '"', '', [rfReplaceAll]);
    if SMasas = '' then SMasas := '-';
    if SCarros = '' then SCarros := '-';
    lblKpiContextoVal.Caption := Format('Masa: %s  |  Carro: %s', [SMasas, SCarros]);

    // KPI 4: Duración
    LDiffSeg := SecondsBetween(LFin, LInicio);
    LMinutos := LDiffSeg div 60;
    LSegundos := LDiffSeg mod 60;
    lblKpiDuracionVal.Caption := Format('%d min %02d s  (%s - %s)', [
      LMinutos, LSegundos,
      FormatDateTime('hh:nn:ss', LInicio),
      FormatDateTime('hh:nn:ss', LFin)
    ]);
  finally
    LMasas.Free;
    LCarros.Free;
  end;
end;

procedure TfrmHorneadoGrafica.ConfigurarColumnasGrid;
var
  I: Integer;
begin
  if not Assigned(dbGridLecturas.DataSource) or not Assigned(dbGridLecturas.DataSource.DataSet) then
    Exit;

  // Formato visual de campos en la pestaña de lecturas
  for I := 0 to qryLecturas.FieldCount - 1 do
  begin
    var F := qryLecturas.Fields[I];
    if SameText(F.FieldName, 'id') then
      F.Visible := False
    else if SameText(F.FieldName, 'fecha_hora') then
    begin
      F.DisplayLabel := 'Fecha y Hora';
      if F is TDateTimeField then
        TDateTimeField(F).DisplayFormat := 'dd/mm/yyyy hh:nn:ss';
    end
    else if SameText(F.FieldName, 'temp_ambiente') then
    begin
      F.DisplayLabel := 'Temp. Horno (°C)';
      if F is TFloatField then
        TFloatField(F).DisplayFormat := '0.00 °C';
    end
    else if SameText(F.FieldName, 'zona1_temp') then
    begin
      F.DisplayLabel := 'Corazón Zona 1 (°C)';
      if F is TFloatField then
        TFloatField(F).DisplayFormat := '0.00 °C';
    end
    else if SameText(F.FieldName, 'numero_masa') then
      F.DisplayLabel := 'Masa'
    else if SameText(F.FieldName, 'numero_carro') then
      F.DisplayLabel := 'Carro'
    else if SameText(F.FieldName, 'bateria') then
    begin
      F.DisplayLabel := 'Batería (%)';
      if F is TNumericField then
        TNumericField(F).DisplayFormat := '0''%''';
    end
    else if SameText(F.FieldName, 'dispositivo') then
      F.DisplayLabel := 'Dispositivo'
    else if SameText(F.FieldName, 'operador') then
      F.DisplayLabel := 'Operador'
    else if SameText(F.FieldName, 'observaciones') then
      F.DisplayLabel := 'Observaciones';
  end;
end;

procedure TfrmHorneadoGrafica.pbChartPaint(Sender: TObject);
var
  C: TCanvas;
  W, H: Integer;
  ChartL, ChartR, ChartT, ChartB: Integer;
  ChartW, ChartH: Integer;
  TMin, TMax: TDateTime;
  SecTotal: Double;
  ValMinY, ValMaxY: Double;
  I: Integer;
  YSteps, S: Integer;
  YVal, YPixel: Double;
  LblStr: string;
  PtX, PtY: Integer;
  SecOffset: Double;
  PointsAmb: array of TPoint;
  PointsZ1: array of TPoint;
  CountAmb, CountZ1: Integer;
  HoverX, HoverYAmb, HoverYZ1: Integer;
  HoverReading: TTempReading;
  TooltipR: TRect;
  TooltipLines: array[0..3] of string;
  LineH: Integer;
begin
  C := pbChart.Canvas;
  W := pbChart.Width;
  H := pbChart.Height;

  // Fondo oscuro pizarra de alta tecnología (#111827 / slate-900)
  C.Brush.Color := $001A1811; // Fondo oscuro elegante
  C.FillRect(Rect(0, 0, W, H));

  if Length(FReadings) = 0 then
  begin
    C.Font.Name := 'Segoe UI';
    C.Font.Size := 12;
    C.Font.Color := clGray;
    C.TextOut(W div 2 - 120, H div 2, 'No hay datos de horneado disponibles para este lote.');
    Exit;
  end;

  // Márgenes del gráfico
  ChartL := 65;
  ChartR := W - 35;
  ChartT := 35;
  ChartB := H - 55;
  ChartW := ChartR - ChartL;
  ChartH := ChartB - ChartT;

  if (ChartW < 50) or (ChartH < 50) then Exit;

  // 1. Calcular límites del eje Y (temperaturas)
  ValMinY := 0.0;
  ValMaxY := 120.0;
  for I := 0 to High(FReadings) do
  begin
    if FReadings[I].HasAmbiente then
      ValMaxY := Max(ValMaxY, FReadings[I].TempAmbiente);
    if FReadings[I].HasZona1 then
      ValMaxY := Max(ValMaxY, FReadings[I].Zona1Temp);
  end;
  // Redondear techo de Y a múltiplo de 20 °C con margen de 10 °C
  ValMaxY := Ceil((ValMaxY + 10.0) / 20.0) * 20.0;
  if ValMaxY < 60.0 then ValMaxY := 60.0;

  // 2. Límites del eje X (tiempo)
  TMin := FReadings[0].FechaHora;
  TMax := FReadings[High(FReadings)].FechaHora;
  SecTotal := Max(1.0, SecondsBetween(TMax, TMin));

  // 3. Dibujar rejilla horizontal y etiquetas del eje Y
  C.Font.Name := 'Segoe UI';
  C.Font.Size := 9;
  YSteps := Round(ValMaxY / 20.0);
  for S := 0 to YSteps do
  begin
    YVal := S * 20.0;
    YPixel := ChartB - (YVal / ValMaxY) * ChartH;

    // Línea de cuadrícula
    C.Pen.Color := $002A241E; // Línea sutil gris azulado
    C.Pen.Style := psSolid;
    C.Pen.Width := 1;
    C.MoveTo(ChartL, Round(YPixel));
    C.LineTo(ChartR, Round(YPixel));

    // Etiqueta de temperatura en el margen izquierdo
    C.Font.Color := $0094A3B8; // Gris pizarra suave
    LblStr := Format('%d °C', [Round(YVal)]);
    C.TextOut(ChartL - C.TextWidth(LblStr) - 10, Round(YPixel) - 7, LblStr);
  end;

  // 4. Dibujar rejilla vertical y etiquetas del eje X (marcas de tiempo)
  var NumTimeTicks := 6;
  for S := 0 to NumTimeTicks do
  begin
    var TickSec := (SecTotal / NumTimeTicks) * S;
    var TickTime := IncSecond(TMin, Round(TickSec));
    var TickX := ChartL + Round((TickSec / SecTotal) * ChartW);

    C.Pen.Color := $0025201A;
    C.MoveTo(TickX, ChartT);
    C.LineTo(TickX, ChartB);

    C.Font.Color := $0094A3B8;
    LblStr := FormatDateTime('hh:nn:ss', TickTime);
    C.TextOut(TickX - (C.TextWidth(LblStr) div 2), ChartB + 8, LblStr);
  end;

  // Marco exterior del gráfico
  C.Pen.Color := $003E3830;
  C.Pen.Width := 1;
  C.MoveTo(ChartL, ChartT);
  C.LineTo(ChartR, ChartT);
  C.LineTo(ChartR, ChartB);
  C.LineTo(ChartL, ChartB);
  C.LineTo(ChartL, ChartT);

  // 5. Preparar arrays de puntos para curvas
  SetLength(PointsAmb, Length(FReadings));
  SetLength(PointsZ1, Length(FReadings));
  CountAmb := 0;
  CountZ1 := 0;

  for I := 0 to High(FReadings) do
  begin
    SecOffset := SecondsBetween(FReadings[I].FechaHora, TMin);
    PtX := EnsureRange(ChartL + Round((SecOffset / SecTotal) * ChartW), ChartL, ChartR);

    if FReadings[I].HasAmbiente then
    begin
      PtY := EnsureRange(ChartB - Round((FReadings[I].TempAmbiente / ValMaxY) * ChartH), ChartT, ChartB);
      if CountAmb >= Length(PointsAmb) then
        SetLength(PointsAmb, CountAmb + 100);
      PointsAmb[CountAmb] := Point(PtX, PtY);
      Inc(CountAmb);
    end;

    if FReadings[I].HasZona1 then
    begin
      PtY := EnsureRange(ChartB - Round((FReadings[I].Zona1Temp / ValMaxY) * ChartH), ChartT, ChartB);
      if CountZ1 >= Length(PointsZ1) then
        SetLength(PointsZ1, CountZ1 + 100);
      PointsZ1[CountZ1] := Point(PtX, PtY);
      Inc(CountZ1);
    end;
  end;

  // 6. Dibujar Curva 1: HORNO / AMBIENTE (Naranja vivo / Amber #F97316 -> $001673F9)
  if CountAmb > 1 then
  begin
    SetLength(PointsAmb, CountAmb);
    C.Pen.Color := $001673F9; // Naranja vivo en BGR
    C.Pen.Width := 3;
    C.Pen.Style := psSolid;
    C.Polyline(PointsAmb);

    // Dibujar puntos / nodos pequeños (con paso para no saturar si hay muchas lecturas)
    C.Brush.Color := $001673F9;
    var LStepAmb := Max(1, CountAmb div 80);
    I := 0;
    while I < CountAmb do
    begin
      C.FillRect(Rect(PointsAmb[I].X - 2, PointsAmb[I].Y - 2, PointsAmb[I].X + 3, PointsAmb[I].Y + 3));
      Inc(I, LStepAmb);
    end;
  end;

  // 7. Dibujar Curva 2: CORAZÓN / ZONA 1 (Azul / Cyan vivo #0284C7 -> $00C78402)
  if CountZ1 > 1 then
  begin
    SetLength(PointsZ1, CountZ1);
    C.Pen.Color := $00E8851B; // Azul cian vibrante en BGR
    C.Pen.Width := 3;
    C.Pen.Style := psSolid;
    C.Polyline(PointsZ1);

    // Dibujar puntos / nodos pequeños (con paso para no saturar si hay muchas lecturas)
    C.Brush.Color := $00E8851B;
    var LStepZ1 := Max(1, CountZ1 div 80);
    I := 0;
    while I < CountZ1 do
    begin
      C.Ellipse(PointsZ1[I].X - 3, PointsZ1[I].Y - 3, PointsZ1[I].X + 4, PointsZ1[I].Y + 4);
      Inc(I, LStepZ1);
    end;
  end;

  // 8. Línea de Inspección y Tooltip flotante interactivo (Crosshair)
  if (FHoverIndex >= 0) and (FHoverIndex < Length(FReadings)) then
  begin
    HoverReading := FReadings[FHoverIndex];
    SecOffset := SecondsBetween(HoverReading.FechaHora, TMin);
    HoverX := EnsureRange(ChartL + Round((SecOffset / SecTotal) * ChartW), ChartL, ChartR);

    // Línea vertical blanca de seguimiento
    C.Pen.Color := clWhite;
    C.Pen.Width := 1;
    C.Pen.Style := psDot;
    C.MoveTo(HoverX, ChartT);
    C.LineTo(HoverX, ChartB);

    // Resaltar puntos activos
    if HoverReading.HasAmbiente then
    begin
      HoverYAmb := EnsureRange(ChartB - Round((HoverReading.TempAmbiente / ValMaxY) * ChartH), ChartT, ChartB);
      C.Pen.Color := clWhite;
      C.Pen.Width := 2;
      C.Brush.Color := $001673F9;
      C.Ellipse(HoverX - 6, HoverYAmb - 6, HoverX + 7, HoverYAmb + 7);
    end;

    if HoverReading.HasZona1 then
    begin
      HoverYZ1 := EnsureRange(ChartB - Round((HoverReading.Zona1Temp / ValMaxY) * ChartH), ChartT, ChartB);
      C.Pen.Color := clWhite;
      C.Pen.Width := 2;
      C.Brush.Color := $00E8851B;
      C.Ellipse(HoverX - 6, HoverYZ1 - 6, HoverX + 7, HoverYZ1 + 7);
    end;

    // Tarjeta Tooltip flotante
    TooltipLines[0] := Format('⏱ %s', [FormatDateTime('hh:nn:ss', HoverReading.FechaHora)]);
    if HoverReading.HasAmbiente then
      TooltipLines[1] := Format('🟠 Horno: %.1f °C', [HoverReading.TempAmbiente])
    else
      TooltipLines[1] := '🟠 Horno: --';

    if HoverReading.HasZona1 then
      TooltipLines[2] := Format('🔵 Corazón: %.1f °C', [HoverReading.Zona1Temp])
    else
      TooltipLines[2] := '🔵 Corazón: --';

    TooltipLines[3] := Format('🏷 Masa: %s | Carro: %s', [HoverReading.Masa, HoverReading.Carro]);

    // Posición del tooltip (a la derecha o izquierda según cercanía al borde derecho)
    var TtWidth := 195;
    var TtHeight := 90;
    var TtX := HoverX + 15;
    if TtX + TtWidth > ChartR then
      TtX := HoverX - TtWidth - 15;

    var TtY := ChartT + 20;

    TooltipR := Rect(TtX, TtY, TtX + TtWidth, TtY + TtHeight);

    // Fondo y borde del Tooltip
    C.Pen.Color := $0038BDF8; // Borde celeste claro
    C.Pen.Width := 2;
    C.Pen.Style := psSolid;
    C.Brush.Color := $001E293B; // Fondo tarjeta pizarra oscura
    C.RoundRect(TooltipR.Left, TooltipR.Top, TooltipR.Right, TooltipR.Bottom, 8, 8);

    // Textos del tooltip
    C.Font.Name := 'Segoe UI';
    C.Font.Size := 9;
    LineH := 19;

    C.Font.Color := clWhite;
    C.Font.Style := [fsBold];
    C.TextOut(TtX + 10, TtY + 8, TooltipLines[0]);

    C.Font.Style := [];
    C.Font.Color := $0038BDF8;
    C.TextOut(TtX + 10, TtY + 8 + LineH, TooltipLines[1]);

    C.Font.Color := $0093C5FD;
    C.TextOut(TtX + 10, TtY + 8 + (LineH * 2), TooltipLines[2]);

    C.Font.Color := $00CBD5E1;
    C.TextOut(TtX + 10, TtY + 8 + (LineH * 3), TooltipLines[3]);
  end;
end;

procedure TfrmHorneadoGrafica.pbChartMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
var
  W, H: Integer;
  ChartL, ChartR, ChartT, ChartB: Integer;
  ChartW: Integer;
  TMin, TMax: TDateTime;
  SecTotal, MouseSec: Double;
  ClosestIdx, I: Integer;
  MinDiff, Diff: Double;
begin
  if Length(FReadings) = 0 then Exit;

  W := pbChart.Width;
  H := pbChart.Height;
  ChartL := 65;
  ChartR := W - 35;
  ChartT := 35;
  ChartB := H - 55;
  ChartW := ChartR - ChartL;

  if (X < ChartL) or (X > ChartR) or (Y < ChartT) or (Y > ChartB) then
  begin
    if FHoverIndex <> -1 then
    begin
      FHoverIndex := -1;
      pbChart.Invalidate;
    end;
    Exit;
  end;

  TMin := FReadings[0].FechaHora;
  TMax := FReadings[High(FReadings)].FechaHora;
  SecTotal := Max(1.0, SecondsBetween(TMax, TMin));

  MouseSec := ((X - ChartL) / ChartW) * SecTotal;

  ClosestIdx := 0;
  MinDiff := 1E9;
  for I := 0 to High(FReadings) do
  begin
    Diff := Abs(SecondsBetween(FReadings[I].FechaHora, TMin) - MouseSec);
    if Diff < MinDiff then
    begin
      MinDiff := Diff;
      ClosestIdx := I;
    end;
  end;

  if (ClosestIdx >= 0) and (ClosestIdx < Length(FReadings)) and (FHoverIndex <> ClosestIdx) then
  begin
    FHoverIndex := ClosestIdx;
    pbChart.Invalidate;
  end;
end;

procedure TfrmHorneadoGrafica.btnExportarCsvClick(Sender: TObject);
var
  SaveDlg: TSaveDialog;
  Lines: TStringList;
  I: Integer;
  LFileName: string;
begin
  if Length(FReadings) = 0 then
  begin
    ShowMessage('No hay datos para exportar.');
    Exit;
  end;

  SaveDlg := TSaveDialog.Create(Self);
  Lines := TStringList.Create;
  try
    SaveDlg.Title := 'Guardar lecturas de horneado';
    SaveDlg.Filter := 'Archivos CSV (*.csv)|*.csv|Todos los archivos (*.*)|*.*';
    SaveDlg.FileName := Format('Horneado_Lote_%s.csv', [FLoteCodigo]);

    if SaveDlg.Execute then
    begin
      LFileName := SaveDlg.FileName;
      if ExtractFileExt(LFileName) = '' then
        LFileName := LFileName + '.csv';

      Lines.Add('Fecha y Hora;Temp. Horno (C);Corazon Zona 1 (C);Masa;Carro;Bateria (%);Dispositivo');
      for I := 0 to High(FReadings) do
      begin
        Lines.Add(Format('%s;%s;%s;%s;%s;%d;%s', [
          FormatDateTime('yyyy-mm-dd hh:nn:ss', FReadings[I].FechaHora),
          StringReplace(FloatToStr(FReadings[I].TempAmbiente), ',', '.', []),
          StringReplace(FloatToStr(FReadings[I].Zona1Temp), ',', '.', []),
          FReadings[I].Masa,
          FReadings[I].Carro,
          FReadings[I].Bateria,
          FReadings[I].Dispositivo
        ]));
      end;
      Lines.SaveToFile(LFileName, TEncoding.UTF8);
      ShowMessage(Format('Exportadas %d lecturas a:' + sLineBreak + '%s', [Length(FReadings), LFileName]));
    end;
  finally
    Lines.Free;
    SaveDlg.Free;
  end;
end;

procedure TfrmHorneadoGrafica.btnCopiarClick(Sender: TObject);
var
  Lines: TStringList;
  I: Integer;
begin
  if Length(FReadings) = 0 then
  begin
    ShowMessage('No hay datos para copiar.');
    Exit;
  end;

  Lines := TStringList.Create;
  try
    Lines.Add('Fecha'#9'Hora'#9'Temp. Horno'#9'Temp. Corazón'#9'Masa'#9'Carro');
    for I := 0 to High(FReadings) do
    begin
      Lines.Add(Format('%s'#9'%s'#9'%.1f'#9'%.1f'#9'%s'#9'%s', [
        FormatDateTime('yyyy-mm-dd', FReadings[I].FechaHora),
        FormatDateTime('hh:nn:ss', FReadings[I].FechaHora),
        FReadings[I].TempAmbiente,
        FReadings[I].Zona1Temp,
        FReadings[I].Masa,
        FReadings[I].Carro
      ]));
    end;
    Clipboard.AsText := Lines.Text;
    ShowMessage(Format('Se han copiado %d lecturas al portapapeles.', [Length(FReadings)]));
  finally
    Lines.Free;
  end;
end;

procedure TfrmHorneadoGrafica.btnCerrarClick(Sender: TObject);
begin
  Close;
end;

end.
